J King
J King

Reputation: 3

Indenting Items When Printing From a File

I am still in the process of learning Python so this may seem like a basic question. I am working through the sample problems out of Python Crash Course. I am attempting to read multiple files and print out/display the contents of each file. I want to have the text "The file contains the following pet names: " print and then have an indented list of the names below.

I'm running into an issue of either only the first item/line in each file indenting or each letter of a line printing on its own individual line.

Here is the code I wrote.

def list_pets(filename):
    """Lists pet names within the file."""
    try:
        with open(filename) as file_object:
            pet_names = file_object.read()
    except FileNotFoundError:
        msg = "Unable to locate file " + filename + "."
        print(msg)
    else:
        print("\nThe file " + filename + " contains the following pets: ")
        pets = ""
        for pet in pet_names:
            pets += pet
        print(pets)

filenames = ['dogs.txt', 'cats.txt', 'birds.txt']
for file in filenames:
    list_pets(file)

Here is the output of the above code (birds.txt was intentionally not in the folder):

The file dogs.txt contains the following pets:
Buttons
Biscuit
Abby
Sam
Jerry
Obi
Roger


The file cats.txt contains the following pets:
Missy
Brown Cat
Oliver
Seal
Mr Bojangles

Unable to locate file birds.txt.

How can I use \t to indent the names? I've tried changing print(pets) to print("\t" + pets) but that seems to only indent the first name.

Thanks in advance! I'm having a lot of fun learning Python but this little booger has me stumped.

Upvotes: 0

Views: 239

Answers (3)

Doc
Doc

Reputation: 11671

 ...
 pet_names = file_object.readlines()  # to split the lines
 ...


 for pet in pet_names:
     pets = pets + "\t" + pet +"\n"
 print(pets)

just add \t before each name and a new line after

Upvotes: 1

Alex Triphonov
Alex Triphonov

Reputation: 1

If you print pet_names just after you read() it- you'll see they all still prints in new line each. That's because read() does not remove line breaks. Also, use format() to format strings. Good luck!

def list_pets(filename):
"""Lists pet names within the file."""
try:
    with open(filename) as file_object:
        pet_names = file_object.read().split('\n')
except FileNotFoundError:
    print("Unable to locate file {}.".format(filename))
else:
    print("The file {} contains the following pets: {}".format(filename, ' ,'.join(pet_names)))

Upvotes: 0

RightmireM
RightmireM

Reputation: 2492

Try this, and see if the tab reports properly:

_list = ["Buttons","Biscuit","Abby","Sam","Jerry","Obi","Roger"]

indent = "\t"
for l in _list:
    print("{}{}".format(indent, l))

Upvotes: 1

Related Questions