Andy
Andy

Reputation: 373

Python CSV seek not working?

 file_handle = open("/var/www/transactions.csv", "a")
  c = csv.writer(file_handle);

 oldamount = amount / 1.98
  file_handle.seek(0);

  c.writerow( [addre, oldamount, "win"])

Here is my code

I wish to write [addre, oldamount, "win"]) to the start of my CSV file, however it's not working. It's still going to the bottom.

Upvotes: 1

Views: 1184

Answers (1)

Christian Aichinger
Christian Aichinger

Reputation: 7237

You are opening the file in append ("a") mode. The documentation for open() points out this behavior explicitly: "all writes append to the end of the file regardless of the current seek position".

It isn't possible to "just insert" text at the beginning of a file like you want to. You can either read the whole file, add your data in the front, and write it back out, or you live with the fact that the data goes at the end.

Example for rewriting:

with open("/var/www/transactions.csv", "r+") as f:
    olddata = f.read()
    f.seek(0)
    c = csv.writer(f);
    c.writerow([addre, oldamount, "win"])
    f.write(olddata)

Note that this can corrupt your file if something goes wrong while writing. If you want to minimize that possibility, write to a new file, then os.rename() it to overwrite the old one.

Upvotes: 3

Related Questions