【问题标题】:Python CSV file read and write with incremental numberPython CSV文件用增量数读写
【发布时间】:2016-01-11 15:18:53
【问题描述】:

有用于输入的 Python CSV 读取文件,包含 2 个值。一个递增的数字和一个名称。

记录以百万计,大部分时间在开始时停止。

如何在写入时记录增量编号,以便从中断的地方继续。

import csv

data = {}
with open("readfile.csv", "r") as f:
     for line in f.readlines():
        num,name = line.strip().split(',')
        data[num] = name


with open("output.csv", "wb") as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(["Number", "Name"])

【问题讨论】:

    标签: python python-2.7 csv


    【解决方案1】:

    一种解决方案是使用 Python 文件 seek() 和 tell() 功能。

    您可以使用tell读取当前位置偏移并将其存储在另一个文件中。

    然后您可以打开文件并使用 seek 移动到该位置。

    示例功能是:

    import os
    
    if not os.path.exists('readfile.csv'):
        with open("readfile.csv", "wb") as read_f:
            with open("position.dat", "wb") as pos_fi:
    
    
    
                    read_f.write('aaa,111\n')
                    read_f.write('bbb,222\n')
                    read_f.write('ccc,333\n')
                    read_f.write('ddd,444\n')
    
                    pos_fi.write('0')
    
    
    data = {}
    
    with open('position.dat', 'rb') as pos_f:
        ps = pos_f.read()
        print 'Position is : ', ps
        p = int(ps)
    
    # open your data file and the position file
    with open('readfile.csv', 'rb') as read_f:
    
            # read the offset position and seek to that location
            read_f.seek(p)
            for line in iter(read_f.readline, ''):
                    num,name = line.strip().split(',')
                    print num, name
                    data[num] = name
    
            position = str(read_f.tell())
    
    # store your new offset position
    with open("position.dat", "wb") as pos:
            pos.write(position)
    

    编辑:

    这个例子现在可以工作了。

    1. 如果您运行代码一次,它将创建文件。

    2. 如果您随后编辑“readfile.csv”并附加更多行,然后再次运行代码。它会从中断处继续,并打印出新的行。

    请注意使用 seek(),然后不能直接在文件对象上使用 readlines()。诀窍是将其包装在上面的迭代器中。

    你必须围绕这个调整你的代码,因为我不确定你到底想读和写什么。

    是的,您可以在附加模式下打开,写入文件末尾。

    【讨论】:

    • 您需要创建一个 position.dat 文件,最初包含一个零“0”
    • 同样 position.dat 应该以读取模式打开,示例已更正
    • position.dat 文件现在递增到 22407081,如何使用它来接续写。
    • 我们可以将 Number 和 Name 写回 output.csv 文件
    • 您不能将文件指针用作插入器,必须这样做:for line in iter(read_f.readline, '') - 我将调整示例
    【解决方案2】:

    csvfile 是一个文件对象,因此您可以使用seektell 函数在文件上移动光标。所以,当你写完后,你可以通过pos = csvfile.tell()获得当前位置;然后,在下一次开幕时,只需执行csvfile.seek(pos)

    请注意,您必须每次都以相同的模式打开文件,才能使用此 pos(二进制文件可能是个好主意)。

    另一个想法是简单地以附加模式打开csvfilewith open('output.csv', 'ab')。这写在文件的末尾。

    【讨论】:

      猜你喜欢
      • 2017-05-25
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      • 2016-10-22
      • 2016-03-21
      相关资源
      最近更新 更多