Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
David Savoir
6,172 PointsHow to read all content of a file in python, while that file is open ?
If a file was open for reading, how would you print the files' contents ? Note: I have already used f.readline/f.readlines so the pointer is already further down the content of the file.
I have thought about using f.seek(0, 0) and then f.read(), but is there any other (better) way ?
Thanks in advance,
2 Answers
Kenneth Love
Treehouse Guest TeacherMost of the time, I'd then loop over the lines in the file, appending them to a variable. Then I can search/print/edit/etc the file contents without having the file open any longer. Something like:
contents = ""
with open('some_file.txt') as f:
for line in f.readlines():
contents += line
Once that for ends, the with will end and that will close the file. Now contents has the entire contents of the file and I can do with it whatever I want.
Ben Stoltz
20,364 PointsHey David!
There are a few ways to go about this depending on the type of file.
For example some ways to do this:
with open('Path/to/file', 'r') as content_file:
content = content_file.read()
Or if you're working with a text file and want to return everything as one line:
with open ("data.txt", "r") as myfile:
data=myfile.read().replace('\n', '')
If you're looking at working with CSV's (excel data, etc) I'd strongly recommend you take a look at the CSV module.
Good luck!