Skip to main content
 首页 » 编程设计

Python CSV文件读写增量数

2024年10月24日9linjiqin

有 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 文件的 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”并附加更多行,然后再次运行代码。它将从停止的地方继续,并打印出新的行。

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

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

是的,您可以只以追加模式打开,写入文件末尾。