I'm a Python beginner, and I'm doing some tests of file operations. I just read a file with read()
and readlines()
. Each of them works perfectly, respectively. However, when I add a readlines()
to read the appointed file after read()
, I surprisingly find that I can't read anything from the file using readlines()
.
PS I tried to switch the places of them, and the latter function can't read anything from the file yet.
So, how do the functions actually work?
Below is my code:
filea = open('/Users/gssflyaway/Documents/web/echarts-2.2.7/LICENSE.TXT')
print filea.readlines()
print '-' * 50
print filea.read()
filea.close()
Files are read from the disk by moving a pointer (like a bookmark so that the file object knows where it left) around. A read operation advances the pointer and if you read the whole file, the pointer will be at the very end of the file. Same applies to both readlines
and read
. If you want to re-read the file, you can use seek
to reset the pointer to the beginning to start a new round.
filea.seek(0)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.