【发布时间】:2015-04-13 23:55:50
【问题描述】:
我陷入了 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 和开发工具是带有 PyDev 3.7.1.xx 的 Eclipse
关于我做错了什么有什么建议吗?
【问题讨论】: