python - 使用r+模式读写同一个文件

标签 python file csv io

我有一个脚本可以成功从 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/

相关文章:

python - 以关键字参数作为线程启动方法

c++ - 从 Windows 上的文件中删除前 N 个字节的最有效方法是什么?

C 删除文件中的重复数字

Python:如何从转换后的 csv 文件创建数据文件?

python - 如何在 pandas 中设置新值但保留原始数据框

python - 在 PyQT4 GUI 中嵌入的 funcAnimation 中使用 blitting

python - numpy 中向量化函数的性能行为

java - 我的文件读取器方法从文件中读取数组列表有什么问题

php - 将mysql数据导出到csv文件

r - 写入制表符分隔文件或 csv 文件