写作&在Python中读取相同的csv文件 [英] Writing & Reading the same csv file in Python

查看:144
本文介绍了写作&在Python中读取相同的csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以写(这里应该是编辑的)使用csv库在Python中同时读取相同的csv文件?



可以打开csv文件进行编辑附加?



如果是,如何?

解决方案

/ p>




详细答案:



使用CSV writer。只需打开附加文件a模式:

  (data.csv,aas fh:
w = csvwriter(fh):
w.writerow(...)

编辑CSV文件并不简单,因为您需要插入和删除文件的某些部分,除非您正在编辑的列是固定长度的。 csv 模块没有内置方法。



您可以打开原始文件,删除(或重命名原始文件)具有相同名称的新文件:

 与文件(data.csv,r)as rfh:
os.remove(data.csv):
r = csvreader(rfh)
文件(data.csv,w)为wfh:
w = csvwriter(wfh)
#...从r读取并写入w

在Linux下,原始文件将保持可用于读取,直到它被关闭的点,所以你不需要预先重命名。我不太熟悉Windows,所以你可能需要重命名原始文件,然后创建新文件,并删除旧文件之后关闭它。






另一个重要的位:如果你的写作没有任何麻烦,你可以读/写同一个文件

 以文件(data.csv,r)作为rfh,file .csv,a)as wfh:
r = csvreader(rfh)
w = csvwriter(wfh)
#你可以使用r和append读取使用w

只要小心 - 您的读者将能够读取您刚刚使用writer写的行。请注意,您不会在无限循环中导致非常大的文件。


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?

解决方案

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.

这篇关于写作&在Python中读取相同的csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆