python循环将不会在第二遍上迭代 [英] python loop won't iterate on second pass

查看:122
本文介绍了python循环将不会在第二遍上迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在Python IDLE Shell中运行以下代码时:

When I run the following in the Python IDLE Shell:

f = open(r"H:\Test\test.csv", "rb")
for line in f:
    print line
    #this works fine

但是,当我第二次运行以下命令时:

however, when I run the following for a second time:

for line in f:
    print line
    #this does nothing


推荐答案

这不工作,因为你已经在第一次到文件末尾。您需要后退(使用 .seek(0))或重新打开您的文件。

This does not work because you've already seeked to the end of the file the first time. You need to rewind (using .seek(0)) or re-open your file.


  1. Python有一个非常好的 csv 模块。

  2. 您可能希望在'rU'中打开您的文件模式,而不是'rb''rU'是通用换行模式,它将处理来自具有不同行结尾的平台的源文件。

  3. code>与在处理文件对象时,因为它会清理你的句柄,即使在错误的情况下。例如:

  1. Python has a very good csv module. Do not attempt to implement CSV parsing yourself unless doing so as an educational exercise.
  2. You probably want to open your file in 'rU' mode, not 'rb'. 'rU' is universal newline mode, which will deal with source files coming from platforms with different line endings for you.
  3. Use with when working with file objects, since it will cleanup the handles for you even in the case of errors. Ex:

with open(r"H:\Test\test.csv", "rU") as f:
    for line in f:
        ...

这篇关于python循环将不会在第二遍上迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆