在 Python 中读取 .csv 而不循环遍历整个文件?
我见过Python的csv.reader使用的唯一方法是在for循环中,它遍历整个文件而不保存变量中读取的过去的值。我一次只需要处理(巨大)文件的连续两行。使用 csv.reader for 循环,我一次只有 1 行。
有没有一种方法可以使用Python的csv模块只读取csv文件的一行,而不必读完文件到最后?
我需要将变量设置为第一行中的值,将第二组变量设置为下一行的值,同时使用两组变量进行计算,然后用第二组变量覆盖第一组变量,然后读取新行以覆盖第二组。
The only way I've seen Python's csv.reader used is in a for loop, which goes through the whole file without saving past values of the read in variables. I only need to work with 2 consecutive lines of the (enormous) file at a time. Using the csv.reader for loop, I only have 1 line at a time.
Is there a way to use Python's csv module for taking in only one line of a csv file without having to finish reading the file to the end?
I need to set variables to the values in the first line, set a second set of variables to the values of the next line, use the two sets of variables simultaneously for computations, then overwrite the first set of variables with the second set, and read a new line to overwrite the second set.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
没有什么强迫您循环使用阅读器。只需阅读第一行,然后阅读第二行。
There's nothing forcing you to use the reader in a loop. Just read the first line, then read the second line.
如果您总是查看连续的两行,那么在我看来,您可能会受益于使用成对 食谱。从 itertools 模块:
您可以像这样使用它:
If you're always looking at exactly two consecutive lines, it sounds to me like you might benefit from using the pairwise recipe. From the itertools module:
You would use this like so:
读取 CSV:
在 Python 2.7 中读取下一行:
在 Python 3.4 中读取下一行:
Read CSV:
Read the next row in Python 2.7:
Read the next row in Python 3.4:
明显的答案似乎是在每次迭代时只存储前一行。
The obvious answer seems to be to just store the previous line on each iteration.
公然窃取 TK... ...剩下的主要问题是,OP 想要对文件的第一行和最后一行做什么?
Blatant stealing from TK... ...mostly the question that remains is, what does the OP want to do with the first and last lines of the file?