文件在python中被覆盖,当在append mod中打开时

2024-10-02 22:35:12 发布

您现在位置:Python中文网/ 问答频道 /正文

WriteFile1()代码片段:

try:
    iOutputFile = open(IFilePath, "a")
    if iOutputFile == 0:
        return

    csvInfoWriter = csv.writer(iOutputFile,  delimiter=',', lineterminator='\n')

    lenBuff = len(g_Hash)
    for value in g_Hash.itervalues():
        iValueLen = len(value)
        for index in range(0, iValueLen):
            csvInfoWriter.writerow(value[index])


    iOutputFile.close()

 except:
    print sys.exc_type

我在读一个文件的内容,把它们存储在dict gĔHash中。在

在读取了1000条记录后,我调用WriteFile1()来写入文件,我会清除dict g_Hash中的内容[通过调用ClearRec()]。每次我调用WriteFile1()时,它都会覆盖我的输出文件。在

请帮帮我,我想追加数据,不想覆盖。。在

编辑:从代码中删除此项后,仍然会出现问题。在

^{pr2}$

更新:

ClearRec()代码:

        WriteFile1()
        g_Hash.clear()

------------ClearRec()是否会导致任何问题?--------在


Tags: 文件代码in内容forindexlenvalue
2条回答

您需要将append更改为“a+”

为了更多的参考 http://docs.python.org/2/library/functions.html#open

Modes 'r+', 'w+' and 'a+' open the file for updating (note that 'w+' truncates the file). Append 'b' to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don’t have this distinction, adding the 'b' has no effect.

拆下以下线路。它总是被认为是错误的。在

if iOutputFile == 0:
    return

Python中的内置open返回文件对象,而不是文件描述符。在

^{pr2}$

相关问题 更多 >