简体   繁体   English

readlines()在使用readline()后无法读取行

[英]readlines() cannot read lines after using readline()

The following simple code reads a CSV file and returns the number of lines of the file. 以下简单代码读取CSV文件并返回文件的行数。 As you can see in the output, the file has 501 lines. 正如您在输出中看到的,该文件有501行。

>>> import codecs
>>> f = codecs.open("tmp.csv", "r", "utf_8")
>>> print len(f.readlines())
501

But if I insert a readline() before using readlines(), the latter does not reach at the end of the file. 但是如果我在使用readlines()之前插入readline(),则后者不会到达文件的末尾。

>>> import codecs
>>> f = codecs.open("tmp.csv", "r", "utf_8")
>>> f.readline()
>>> print len(f.readlines())
1

Is there any basic mistake in my code? 我的代码中有任何基本错误吗? How can I mix readline() and readlines()? 如何混合readline()和readlines()? (actually I don't need to mix these two functions in my real program, but I am just curious...) (实际上我不需要在我的真实程序中混合这两个函数,但我只是好奇...)

You can download the file at https://dl.dropboxusercontent.com/u/16653989/tmp/tmp.csv 您可以在https://dl.dropboxusercontent.com/u/16653989/tmp/tmp.csv下载该文件

This has something to do with the codecs module. 这与codecs模块有关。 Because when you do the same thing with the regular python open statement, it works as expected: 因为当你使用常规的python open语句做同样的事情时,它按预期工作:

f = open('tmp.csv')
f.readline()
>>> print len(f.readlines())
500

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

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