2

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? --------

Emma
  • 617
  • 2
  • 12
  • 29
  • 1
    @Talvalin No, that's Java. – Deestan Jul 04 '13 at 13:44
  • its python, not java. All functionality works file, just overwrite problem. – Emma Jul 04 '13 at 13:59
  • You may have to post all of your code (if it's long then add a pastebin link). I wrapped the snippet in a function (without the try/except) and called WriteFile1() twice with a different dictionary and no overwriting occurred. I used Python 2.7.3 running on Windows 7. – Talvalin Jul 04 '13 at 15:47

2 Answers2

3

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.

Steve
  • 21,163
  • 21
  • 69
  • 92
2

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
falsetru
  • 357,413
  • 63
  • 732
  • 636