0

我正在寻找一个 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,所以不确定我是否以错误的方式进行操作,也理解这个示例非常简单,但我似乎无法理解它的逻辑.

请温柔一点;)

4

2 回答 2

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)
于 2020-07-23T00:50:17.803 回答
0

为什么你不使用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')
于 2020-07-23T01:07:41.110 回答