首页 > 解决方案 > 在不删除所有内容的情况下修改 csv 文件的特定行的最佳方法是什么?

问题描述

我有一个用记事本打开的 csv 文件:

在此处输入图像描述

我想修改我的 csv 以将第 4 行替换为“温度水平波度”:

在此处输入图像描述 我的代码:

                with open(file.csv, 'w') as m:
                content = m.readlines()
                line_4 = (content[3])

                line_4.replace(line_4, 'Temperature Level Wave Degre')

我的 csv 是空的!

在不删除所有内容的情况下修改 csv 文件的特定行的最佳方法是什么?最有效的代码?

谢谢你。

标签: python-3.xpandasdataframe

解决方案


这是使用 python 的解决方案,但是正如我在评论中提到的,可能有更有效的命令行工具(我会使用awk

with open(filename, 'r+') as f:
    lines = f.readlines()                        # read lines and store in list
    lines[3] = 'Temperature Level Wave Degre\n'  # change line 4, don't forget to add a newline
    f.seek(0)                                    # come back to beginning of file
    f.writelines(lines)                          # write the new lines
    f.truncate()                                 # ensure we don't keep old stuff from the previous file

推荐阅读