Opening File Object With Python: Readlines() And Readline() Does Not Return Any Value
I have a problem returning values using readlines() and readline(), but not with read(). Any one knows how this can happen? Appreciate it with open('seatninger.txt', 'r') as f: # o
Solution 1:
You have exausted the file with read
, so you need to go back to read it again using seek:
f_contents = f.read()
f.seek(0)
f_contents_list = f.readlines()
f.seek(0)
f_contents_line = f.readline()
Python goes through the file, reads data and remembers where it stopped.
When you use read()
it reads whole file and it stops at the end of the file.
When you use readlines()
it reads whole file, splits it on newline character and returns the list.
When you use readline()
it reads and returns next line, remembering where it stopped reading, distinguishing lines based on newline character.
Post a Comment for "Opening File Object With Python: Readlines() And Readline() Does Not Return Any Value"