0

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
J King
  • 3
  • 2
  • See [How to indent the contents of a multi-line string?](https://stackoverflow.com/questions/8234274/how-to-indent-the-contents-of-a-multi-line-string) – martineau Oct 18 '19 at 18:44

3 Answers3

1
 ...
 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

Doc
  • 10,831
  • 3
  • 39
  • 63
  • I updated my code to this: `print("\nThe file " + filename + " contains the following pets: ") pets = "" for pet in pet_names: pets = pets + "\t" + pet print(pets)` and got the following: – J King Oct 18 '19 at 18:43
  • `The file dogs.txt contains the following pets: B u t t o n s B i s c u i t A b b y S a m J e r r y O b i R o g e r ` Sorry, the formatting is weird. It put a tab between each letter of the names. – J King Oct 18 '19 at 18:44
  • This latest iteration still prints each letter on it's own line but at least each letter is indented! We're halfway there! I appreciate the help! – J King Oct 18 '19 at 18:52
  • change `pet_names = file_object.read()` to `pet_names = file_object.readline()` and check – Doc Oct 18 '19 at 18:53
  • now if changing gives you an extra line after each name then remove the `\n` from my code. – Doc Oct 18 '19 at 18:54
  • I swapped readline to readlines and kept this chunk: `for pet in pet_names: pets += "\t" + pet print(pets) ` It worked! Thank you so much! – J King Oct 18 '19 at 18:57
  • I'm not sure what the proper etiquette is. But I really appreciate your help. I was wracking my brain over this one. – J King Oct 18 '19 at 19:00
  • Ahhh! If you change it so show `readlines()` instead of `read()`, that's what did the trick. – J King Oct 18 '19 at 19:04
1

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))
RightmireM
  • 2,381
  • 2
  • 24
  • 42
0

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)))
Alex Triphonov
  • 1
  • 1
  • 1
  • 3