Python CSV文件使用增量编号进行读写

时间:2016-01-11 15:18:53

标签: python python-2.7 csv

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"])

2 个答案:

答案 0 :(得分:1)

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

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

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

示例功能将是:

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'并追加更多行,请再次运行该代码。它将从中断处开始,并打印出新的线条。

  3. 请注意使用seek(),您不能直接在文件对象上使用readlines()。诀窍是将它包装在迭代器中,如上所述。

    你必须调整你的代码,因为我不确定你想要读写什么。

    是的,你可以在追加模式下打开,写到文件的末尾。

答案 1 :(得分:1)

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

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

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

相关问题