file io - Python read() function returns empty string -


if type in python:

open("file","r").read() 

sometimes returns exact content of file string, other times returns empty string (even if file not empty). can explain depend on?

when reach end of file (eof) , .read method returns '', there no more data read.

>>> f = open('my_file.txt') >>> f.read() # read entire file 'my file has data.' >>> f.read() # you've reached end of file  '' >>> f.tell() # give current position @ file 17 >>> f.seek(0) # go starting position >>> f.read() # , read file again 'my file has data.' 

doc links: read() tell() seek()

note: if happens @ first time read file, check file not empty. if it's not try putting file.seek(0) before read.


Comments

Popular posts from this blog

c++ - Function signature as a function template parameter -

algorithm - What are some ways to combine a number of (potentially incompatible) sorted sub-sets of a total set into a (partial) ordering of the total set? -

How to call a javascript function after the page loads with a chrome extension? -