python - 同时读取和写入 CSV 文件
问题描述
我想从 csv 文件中读取一些输入,然后修改输入并将其替换为新值。为此,我首先读取了该值,但由于我想修改文件中存在的所有值,所以我被困在了这一点上。那么是否可以在一个 for 循环中以 r 模式打开文件,然后在另一个循环中立即以 w 模式打开文件以输入修改后的数据?
如果有更简单的方法可以做到这一点,请帮助我
谢谢你。
解决方案
是的,您可以在同一个程序中以不同的模式打开同一个文件。请确保不要同时进行。例如,这是完全有效的:
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
正如其他人在评论中指出的那样,同时在同一个文件句柄上读取和写入通常是一个坏主意,并且不会像您期望的那样工作(除非对于一些非常具体的用例)。
推荐阅读
- python - 编写通用代码来构造元组和命名元组
- python - Docker 连接到“现有”数据库,但显示为空
- c# - DLL 中的函数总是返回 null
- python - (Python 3.2): if 语句不满足条件时退出
- mysql - InnoDB 全文搜索死锁
- angular - 发生未处理的异常:无法从“/project 到 docker 中找到模块“@angular-devkit/build-angular”
- mongodb - Mongoose 通过计数对元素进行排序
- python - Pandas DataFrames If else 条件多列
- android - Flutter Firebase:地图类型与子集合
- mysql - mysql唯一约束因空值而失败?