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.