我有一个脚本可以成功从 csv 文件中删除列。目前它通过创建一个新文件来实现这一点。我希望它写入原始文件而不是创建新文件。 我已经尝试过使用 r+ 模式打开,但它没有按我想要的方式工作。请参阅下面的注释。我认为 r+ 模式是我需要的模式,但我正在努力寻找可供学习的工作示例。
我的代码:
import csv
in_file = "Path to Source"
out_file = "Path to Result"
with open(in_file, 'r', newline='') as inf, \
open(out_file, 'w', newline='') as outf:
reader = csv.reader(inf)
writer = csv.writer(outf)
for r in reader:
writer.writerow((r[0],r[1],r[2],r[3],r[4],r[5],r[6]))
尝试使用r+
模式:
with open(in_file, 'r+', newline='') as inf:
reader = csv.reader(inf)
writer = csv.writer(inf)
for r in reader:
writer.writerow((r[0],r[1],r[2],r[3],r[4],r[5],r[6]))
此操作失败,并出现错误列表索引超出范围
最佳答案
据我所知,读者在阅读时,作者也在写作。在同一个文件上。
文件有一个“光标”,即读取/写入文件的当前位置。
因此,写入者将覆盖文件中读者刚刚读取的行之后的下一行,这会对后续读取造成灾难性后果。
我认为第一种方法是最好的:创建一个新文件,然后重命名它(原始输入文件会自动删除)
import csv, os
in_file = "Path to Source"
out_file = "Path to Result"
with open(in_file, 'r', newline='') as inf, \
open(out_file, 'w', newline='') as outf:
reader = csv.reader(inf)
writer = csv.writer(outf)
for r in reader:
writer.writerow(r[:7])
os.rename(out_file, in_file)
关于python - 使用r+模式读写同一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34699944/