我遇到了python中I / O的一个非常基本的问题。我想在现有文件(称为ofe,输出文件)中插入一些行,根据用户传递的参数从源文件(称为ife,输入文件)中提取,存储在名为lineRange的列表中(具有索引idx)和值lineNumber)。 这是结果:
for ifeidx,ifeline in enumerate(ife,1): #for each line of the input file...
with open(outFile,'r+') as ofe:
for idx,lineNumber in enumerate(lineRange,1): #... check if it's present in desired list of lines...
if (ifeidx == lineNumber): #...if found...
ofeidx = 0
for ofeidx, ofeline in enumerate(ofe,1):
if (ofeidx == idx): #...just scroll the the output file and find which is the exact position in desired list...
ofe.write(ifeline) #...put the desired line in correct order. !!! This is always appending at the end of out file!!!!
break
问题是,write()方法始终指向文件末尾,在滚动输出文件时附加行而不是插入行。 我真的不明白发生了什么,因为文件在读+写(r +)模式下打开,既没有附加(a)也没有读取+附加(r + a)模式,。 我也知道代码将(应该)覆盖输出文件行。其他信息是OS WIndow7,Python版本2.7和开发工具是Eclipse与PyDev 3.7.1.xx
有关我做错的任何建议吗?
答案 0 :(得分:0)
您可以从readlines()读取整个文件开始,它将返回一个列表。之后你只需要做list.insert(索引,值)并再次将其写回文件。
with open(outFile, "r") as f:
data = f.readlines()
data.insert(index, value)
with open(outFile, "w+") as f:
f.write(data)
当然,如果你正在处理一个庞大的文件,你应该改变这种方法。
顺便说一下,如果你没有使用with
语句,你应该最后关闭文件。