首页 > 解决方案 > 同时读取和写入 CSV 文件

问题描述

我想从 csv 文件中读取一些输入,然后修改输入并将其替换为新值。为此,我首先读取了该值,但由于我想修改文件中存在的所有值,所以我被困在了这一点上。那么是否可以在一个 for 循环中以 r 模式打开文件,然后在另一个循环中立即以 w 模式打开文件以输入修改后的数据?

如果有更简单的方法可以做到这一点,请帮助我

谢谢你。

标签: pythonpython-3.x

解决方案


是的,您可以在同一个程序中以不同的模式打开同一个文件。请确保不要同时进行。例如,这是完全有效的:

with open("data.csv") as f:
  # read data into a data structure (list, dictionary, etc.)
  # process lines here if you can do it line by line

# process data here as needed (replacing your values etc.)

# now open the same filename again for writing
# the main thing is that the file has been previously closed
# (after the previous `with` block finishes, python will auto close the file)
with open("data.csv", "w") as f:
  # write to f here

正如其他人在评论中指出的那样,同时在同一个文件句柄上读取和写入通常是一个坏主意,并且不会像您期望的那样工作(除非对于一些非常具体的用例)。


推荐阅读