有没有办法将今天的日期和 'file-2' 添加到 csv 中的每一行?
Is there a way to add today's date and 'file-2' to every row in a csv?
我有一个 csv 文件 [没有 header]:
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)
我建议为此使用 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)
如果您需要使用 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)
我有一个 csv 文件 [没有 header]:
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)
我建议为此使用 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)
如果您需要使用 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)