I’ve been at this one for a couple days. Here’s what I’m trying to do:
- Open an already existing csv file in append mode
- Add a string of new lines of csv to the bottom (‘buffer’ below)
- Close the file
- Rename the file reflecting the date of the last data entered.
Snippet of my code:
if mode == 'a':
print buffer
print fn
f = open(fn,mode)
f.write(buffer)
#f.write("\nfoo,bar")
f.close()
print f.closed
os.rename(".\\out\\" + fn, ".\\out\\" + fn[0:17]+tdy[0:4]+ "_" + tdy[5:7] + "_" + tdy[8:10] + ".csv")
Additional info:
-
mode indeed == ‘a’ it gets to the loop.
-
bufferprints. prints as a string of multiline csv data like:foo, bar, foo, bar foo, bar, foo, bar foo, bar, foo, bar -
fnis the correct filename I’m trying to open and prints as such. -
f.closedreturnsTrue -
os.renameworks and renames the file. when I open it, buffer has not been appended. -
I’ve tried adding a
flush()before close. -
I’ve tried it without the rename.
-
I’ve tried to append a hard coded string.
Any ideas?
You are dealing with two files here.
You open
fnfor writing in the current directory, but you rename the file'.\out\' + fn.When opening
fn, make sure you use the correct directory:Note that on Windows, you can use the
/separator as well, which is easier to deal with as you don’t have to use raw strings or escape the slashes. Also, it’s better to useos.path.join()to deal with directories and files:then work with
filenamethroughout the function.