【问题标题】:Python CSV reader doesnt have any dataPython CSV阅读器没有任何数据
【发布时间】:2014-06-20 04:38:05
【问题描述】:

以下代码可以正常工作。

with open(filename, 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        cur.execute(insertStatement, row)

当我插入这两行时,出了点问题。

with open(filename, 'rb') as f:
    reader = csv.reader(f)
    totalrows = len(list(reader))
    print totalrows # Print out the correct output
    for row in reader:
        cur.execute(insertStatement, row)   

我的猜测是,当我分配 totalrows = len(list(reader)) 光标移动到文件的末尾,for 循环中没有任何反应。

如果这是真的,我如何在不关闭文件并重新打开文件的情况下将光标移回开头?如果没有请帮忙。

【问题讨论】:

    标签: python list csv


    【解决方案1】:

    没错,文件已被消费,后续对reader的读取不会返回数据。

    您可以通过在基础文件上调用 f.seek(0) 来解决此问题,即

    with open(filename, 'rb') as f:
        reader = csv.reader(f)
        totalrows = len(list(reader))
        print totalrows # Print out the correct output
        f.seek(0)
        for row in reader:
            cur.execute(insertStatement, row)
    

    【讨论】:

    • @M.ofCA : Blair 在answer 中强调了关于不要两次读取文件的重要观点
    【解决方案2】:

    与其阅读一次,创建并丢弃一个列表,然后再次阅读,为什么不保留该列表并对其进行迭代?

    with open(filename, 'rb') as f:
        reader = csv.reader(f)
        allrows = list(reader)
        totalrows = len(allrows)
        print totalrows # Print out the correct output
        for row in allrows:
            cur.execute(insertStatement, row)   
    

    此外,许多数据库允许您一次插入多条记录,这通常比一次插入一条记录要快。检查您正在使用的任何数据库库的文档。

    【讨论】:

      【解决方案3】:

      如果发生这种情况,请尝试使用 f.seek(0) 将光标放回开头。

      with open(filename, 'rb') as f:
      reader = csv.reader(f)
      totalrows = len(list(reader))
      print totalrows # Print out the correct output
      f.seek(0)  # Moves pointer back to beginning of file
      for row in reader:
          cur.execute(insertStatement, row)  
      

      【讨论】:

        猜你喜欢
        • 2016-12-15
        • 2011-06-18
        • 2018-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多