【问题标题】:Is there a way to add today's date and 'file-2' to every row in a csv?有没有办法将今天的日期和“file-2”添加到 csv 中的每一行?
【发布时间】:2021-09-29 13:21:25
【问题描述】:

我有一个 csv 文件 [没有标题]:

1,0,1,a
2,1,2,b
3,4,5,c

如何将其转换为包含今天日期和 file-2 的格式?

1,0,1,a,2021-07-22,file2
2,1,2,b,2021-07-22,file2
3,4,5,c,2021-07-22,file2

这可能吗? 当我尝试使用 csvwriter 时,我只能追加到结尾。

with open("temp_csv.csv","a") as fout:
    writer = csv.writer(','+date+',file2\n')
    print(writer)

【问题讨论】:

  • 是的,有办法。 Stackoverflow 不是免费的编码服务,也不打算取代现有的教程或文档。您应该发送honest attempt at the solution,然后然后在必要时询问有关它的具体问题。
  • 使用熊猫...会更容易
  • 在这种情况下,它是一个 csv 文件这一事实是无关紧要的。只需打开文件,逐行阅读并适当附加即​​可。您需要将整个文件读入内存(如果文件很大,则将其读入暂存文件),然后重新写入原始文件
  • 是的,我们如何逐行阅读? @AndyKnight
  • 文件对象是可迭代的,所以for line in input_file: ... 注意你必须将数据附加到每一行。

标签: python csv file date export-to-csv


【解决方案1】:

如果您需要使用 CSV 模块,则可以。

您的问题是您试图就地操纵 csv。相反,您应该读取每一行,处理该行,然后将其写入新的输出 csv 文件。

import csv
from datetime import datetime

todays_date = datetime.today().strftime('%Y-%m-%d')

with open("in.csv","r") as fin, open("out.csv", 'w', newline='') as fout:
    reader = csv.reader(fin)
    writer = csv.writer(fout)
    for line in reader:
        line.append(todays_date)
        line.append("file2")
        writer.writerow(line)

【讨论】:

  • 这种方法比 pandas 快吗?另外,非常感谢!
  • 我几乎可以肯定它不会。如果我这样做(如上所述的简单情况),我只需打开文件并将所需的文本附加到每一行,然后将结果写入一个新文件(与上面相同,不使用 csv)。虽然这是一个 csv 文件,但您不需要利用 CSV 模块,因为您正在执行的任务本质上与逗号分隔无关。
  • 知道了,所以它基本上是针对这种类型的用例的。谢谢克里斯!
  • 没问题。我对它们进行了计时 - 对于这个用例(小 csv),CSV 方法更快,但是,随着输入 csv 文件变得更大,pandas 变得更快。话虽如此,小文件的边距是如此之小,这无关紧要!
【解决方案2】:

我建议为此使用 pandas 库。

首先,使用 pandas 将文件加载为数据框 df

import pandas as pd

df = pd.read_csv('temp_csv.csv', header=None, index_col=0)

然后添加你想要的列

df['date'] = ['2021-07-22' for i in range(len(df))]
df['file'] = ['file2' for i in range(len(df))]

最后,保存你的 csv

df.to_csv('temp_csv.csv', header=False)

【讨论】:

  • 谢谢,我们为什么要设置 index_col = 0?有必要吗?
  • pandas 否则会自动添加另一个索引列。您也可以删除index_col=0,并在保存时删除附加列(在df.to_csv
猜你喜欢
  • 1970-01-01
  • 2022-06-16
  • 2019-10-28
  • 1970-01-01
  • 2021-06-16
  • 1970-01-01
  • 2021-08-15
  • 2021-01-23
  • 2020-11-08
相关资源
最近更新 更多