【问题标题】:python write method appendpython写方法追加
【发布时间】: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

关于我做错了什么有什么建议吗?

【问题讨论】:

    标签: python eclipse append


    【解决方案1】:

    您可以从使用 readlines() 读取整个文件开始,这将返回一个列表。之后,您只需要执行 list.insert(index, value) 并将其再次写回文件即可。

    with open(outFile, "r") as f:
        data = f.readlines()
    
    data.insert(index, value)
    
    with open(outFile, "w+") as f:
        f.write(data)
    

    当然,如果您正在处理一个巨大的文件,您应该改变这种方法。

    顺便说一句,如果你没有使用with 语句,你应该在最后关闭文件。

    【讨论】:

    • 感谢您的建议,我也考虑了另一种方法,但是处理非常大的文件的可能性使我不希望将整个输入文件作为列表加载到内存中。尽管如此,您的帮助仍然很感激。
    猜你喜欢
    • 1970-01-01
    • 2020-01-24
    • 1970-01-01
    • 2017-02-06
    • 2014-10-31
    • 2014-06-13
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    相关资源
    最近更新 更多