Emma
Emma

Reputation: 657

file is overwriten in python,when open in append mode

WriteFile1() Code snip:

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

I'm reading one files contents, storing those in dict g_Hash.

After reading 1000 records,I'm calling WriteFile1() to write file, and I do clear contents from dict g_Hash [By calling ClearRec() ]. Everytime I do call WriteFile1() it overwrites my outputfile.

Please help me, I want to append the data, not wanted to overwrite..

Edit: After removing this from code, still the problem occurs.

 if iOutputFile == 0:
        return

Update:

ClearRec() Code:

        WriteFile1()
        g_Hash.clear()

----------- Does ClearRec() will cause any problem? --------

Upvotes: 2

Views: 2652

Answers (2)

Steve
Steve

Reputation: 21509

You need to change the append to "a+"

For a little more reference 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.

Upvotes: 3

falsetru
falsetru

Reputation: 369424

Remove following line. It always be evaluated as False.

if iOutputFile == 0:
    return

Builtin open in Python return file object, not file descriptor.

>>> f = open('1', 'a')
>>> f
<open file '1', mode 'a' at 0x000000000281C150>
>>> type(f)
<type 'file'>
>>> f == 0
False

Upvotes: 2

Related Questions