How do I get this code to print out it's contents?

https://www.codecademy.com/courses/learn-python-3/lessons/learn-python-files/exercises/appending-to-a-file

with open('cool_dogs.txt', 'a') as cool_dogs_file:
  cool_dogs_file.write('Air Buddy')
print(cool_dogs_file)

The output is:

<_io.TextIOWrapper name='cool_dogs.txt' mode='a' encoding='UTF-8'>

How can I get it to print out what’s inside of it?

1 Like

I think the question you’re asking is how do I open and read a file in python (you can check google this way for many examples. In the example you show, the goal is to write a file. That’s why it doesn’t work to print cool_dogs_file.

Here’s a boring example :sweat_smile:

file_you_want_to_read = open("pitabread.txt")
print(file_you_want_to_read.read())

# this would print the glorious pita bread recipes in pitabread.txt
2 Likes

So, if I wanted to then print out cool_dogs_file, could I do something like this:

with open('cool_dogs.txt', 'a') as cool_dogs_file:
  cool_dogs_file.write('Air Buddy')
cl_dg_file = open(cool_dogs_file).read()
print cl_dg_file

Almost. It depends on the file. I’m assuming you want to read cool_dogs.txt.

It would look like this:

f = open("cool_dogs.txt")
print(f.read())

Why can’t I use cool_dogs_file? I opened “cool_dog.txt” as it?

And, also, after pasting that code I can see the contents, but every time I press run it keeps appending ‘Air Buddy’. Is there a way to stop this?

Why can’t I use cool_dogs_file? I opened “cool_dog.txt” as it?

My rule of thumb is, there’s no need to add code when I don’t have a reason for it. That’s why if I just want to read a file I’ll just do that. If I created some alias before for it, sure, I’d use it of course (so it’s fine if it works for you!).

As to stop it from appending… you can maybe clone a copy before if you really wanted to separate the actions. Maybe? Is it just to tinker around?

1 Like

Yeah it is. Just wanted to know if it was possible.

1 Like

cool_dogs_file is a file object which behaves like most objects and has its own set of methods, it’s not just a long data stream of that file.

Attempting to print it will just print whatever the __str__ or __repr__ method returns. As per the other comments it does have methods which allow you to read the contents of the file which you could then print as needed. It’s worth noting though that after the with statement has executed its suite that file is effectively closed so a lot of methods won’t behave as you expect if you use them after that code block.

2 Likes

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.