Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing & Reading the same csv file in Python

Can we write on (Here it should be editting infact) & read the same csv file at the same time in Python using the csv library?

Can a csv file be opened for editing & appending?

If so, how?

like image 479
maheshakya Avatar asked Feb 20 '13 11:02

maheshakya


1 Answers

Short answer: no


Long answer: it depends

Appending data is perfectly possible using the CSV writer. Just open the file in append "a" mode:

with file("data.csv", "a" as fh:
    w = csvwriter(fh):
    w.writerow(...)

Editing a CSV file is not that simple as you will need to insert and remove parts of the file unless the columns you are editing are fixed length. The csv module has no builtin method for this.

You can open the original file, remove (or rename the original file) and open a new file with the same name:

with file("data.csv", "r") as rfh:
    os.remove("data.csv"):
    r = csvreader(rfh)
    with file("data.csv", "w") as wfh:
        w = csvwriter(wfh)
        # ... read from r and write to w

Under Linux the original file will stay available for reading until the point when it is closed, so you do not need to rename it beforehand. I'm not too familiar with windows so you might need to rename the original file before creating the new file and remove the old file after closing it.


Another important bit: You can read and write from/to the same file without any troubles if your writing is limited to appending data.

with file("data.csv", "r") as rfh, file("data.csv", "a") as wfh:
    r = csvreader(rfh)
    w = csvwriter(wfh)
    # you can read using r and append using w

Just be careful - your reader will be able to read the lines that you have just written using the writer. Be careful that you do not end up in an infinite loop causing a very big file.

like image 168
bikeshedder Avatar answered Oct 05 '22 15:10

bikeshedder