【问题标题】:CSV Python - reading a CSV and writing the exact file back with one column changedCSV Python - 读取 CSV 并在更改一列的情况下写回确切的文件
【发布时间】:2020-11-12 15:25:14
【问题描述】:

我正在寻找一个 CSV 文件并对其中的数据进行一些计算(我已经完成了那部分)。 之后,我需要将所有数据完全按照原始文件的方式写入一个新文件,但其中一列将更改为计算结果。

我无法显示实际代码(机密性问题),但这里是代码示例。

headings = ["losts", "of", "headings"]
with open("read_file.csv", mode="r") as read,\
    open("write.csv", mode='w') as write:
    reader = csv.DictReader(read, delimiter = ',')
    writer = csv.DictWriter(write, fieldnames=headings)

    writer.writeheader()
    for row in reader:
        writer.writerows()

在这个阶段,我只是想在“写”中返回与“读”中相同的 CSV

任何帮助将不胜感激,我没有经常使用 CSV,所以不确定我是否以错误的方式进行操作,也理解这个示例非常简单,但我似乎无法理解它的逻辑。

请温柔一点;)

【问题讨论】:

    标签: python csv write


    【解决方案1】:

    你真的很亲密!

    headings = ["losts", "of", "headings"]
    with open("read_file.csv", mode="r") as read, open("write.csv", mode='w') as write:
        reader = csv.DictReader(read, delimiter = ',')
        writer = csv.DictWriter(write, fieldnames=headings)
    
        writer.writeheader()
        for row in reader:
            # do processing here to change the values in that one column
            processed_row = some_function(row)
            writer.writerow(processed_row)
    

    【讨论】:

    • 谢谢你,它帮助我离目标更近了一点,谢谢
    【解决方案2】:

    为什么不使用pandas

    import pandas as pd
    csv_file = pd.read_csv('read_file.csv')
    # do_something_and_add_a_column_here()
    csv_file.to_csv('write_file.csv')
    

    【讨论】:

    • 我不能使用 pandas,这个工具必须在工作服务器上运行,而且他们不会为此安装 Py 包到服务器,它必须在原生 Python 库中完成
    猜你喜欢
    • 1970-01-01
    • 2021-10-30
    • 2017-05-17
    • 2019-10-05
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多