一种解决方案是使用 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)
编辑:
这个例子现在可以工作了。
如果您运行代码一次,它将创建文件。
如果您随后编辑“readfile.csv”并附加更多行,然后再次运行代码。它会从中断处继续,并打印出新的行。
请注意使用 seek(),然后不能直接在文件对象上使用 readlines()。诀窍是将其包装在上面的迭代器中。
你必须围绕这个调整你的代码,因为我不确定你到底想读和写什么。
是的,您可以在附加模式下打开,写入文件末尾。