简体   繁体   English

在Python中使用readlines错误代码吗?

[英]Is using readlines in Python bad code?

I got downvoted for an answer using file.readlines. 我对使用file.readlines的答案不满意。 The critic said that using readlines is crap code (along with other very rude statements). 评论家说,使用readlines是胡扯的代码(以及其他非常粗鲁的声明)。

Is it so bad? 真的好不好吗

I assume that the problem was the fact that readlines() loads the whole file into memory, which - theoretically - can be a lot. 我认为问题是readlines()将整个文件加载到内存中的事实,从理论上讲,这可能很多。

A lazy approach (iterating over the file and reading progressively as needed) is indeed better in terms of memory usage. 懒惰的方法(遍历文件并根据需要逐步读取)确实在内存使用方面更好。 Not sure about efficiency, though. 但是,不确定效率。

Well, bad and bad. 好,坏,坏。 But it loads the whole file in memory which can be a problem, and there is a much better way: 但是它会将整个文件加载到内存中,这可能是个问题,还有更好的方法:

 for line in file:

That will do the same as 这将与

 for line in file.xreadlines():

Which is a version of readlines() that doesn't read the whole file in memory. 这是readlines()的版本,不会读取内存中的整个文件。 It also works in Python 3 as an added bonus, while xreadlines() doesn't. 它还可以在Python 3中作为附加功能工作,而xreadlines()则不能。

So no matter if it's "bad" or not, there is no reason to use it, like ever. 因此,无论它是否“不好”,都没有理由像以往一样使用它。 So don't. 所以不要这样 :) :)

No, readlines is fine. 不, readlines很好。 You just have to remember, that the whole file is stored in memory at one point. 您只需要记住, 整个文件会一次存储在内存中。

No, it is not. 不它不是。 On the other hand, you can use xreadlines to have faster code. 另一方面,您可以使用xreadlines获得更快的代码。

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

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