简体   繁体   English

在Python中读取文件时,read()和readlines()可以一起使用吗?

[英]Can read() and readlines() work together when reading a file in Python?

I'm a Python beginner, and I'm doing some tests of file operations. 我是Python初学者,正在做一些文件操作测试。 I just read a file with read() and readlines() . 我只是用read()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() . 但是,当我在read()之后添加readlines()来读取指定的文件时,我惊讶地发现我无法使用readlines()从文件中读取任何内容。

PS I tried to switch the places of them, and the latter function can't read anything from the file yet. PS我试图切换它们的位置,而后者功能还无法从文件中读取任何内容。

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()

the result by Pycharm Pycharm的结果

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 . 同样适用于readlinesread If you want to re-read the file, you can use seek to reset the pointer to the beginning to start a new round. 如果要重新读取文件,则可以使用seek将指针重置为开始新的一轮。

filea.seek(0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM