英文:
Adding new column with the header containing date at the beginning of CSV file
问题
我在Stackoverflow上搜索了这个问题,但没有找到我想要的确切答案。我想要在Python中打开csv文件,并添加一个名为"Date"的新列,然后在文件的末尾添加今天的日期。我应该如何做呢?我尝试使用pandas来实现,但我只知道如何将数据附加到末尾。
我尝试使用csv包这样做:
x = open(outfile_name1)
y = csv.reader(x)
z = []
for row in y:
z.append(['0'] + row)
在['0']的位置,我想要放入今天的日期。然后,我能够使用pandas或其他方法将此列表转换为csv吗?提前感谢您的帮助!
英文:
I was looking on Stackoverflow for this thing but I didn't find exactly what I wanted. I would like to open csv file on Python and add new column with header "Date" and until end of the file add today's date. How can I do it? I was trying to do it with pandas but I only know how to append to the end.
I was trying to do this that way with package csv:
x=open(outfile_name1)
y=csv.reader(x)
z=[]
for row in y:
z.append(['0'] + row)
Instead of ['0'] I wanted to put today's date. Can I then convert this list to csv with pandas or something? Thanks in advance for help!
答案1
得分: 3
尝试这个:
import pandas as pd
import datetime
df = pd.read_csv("my.csv")
df.insert(0, 'Date', datetime.datetime.today().strftime('%Y-%m-%d'))
df.to_csv("my_withDate.csv", index=False)
附注:阅读文档
英文:
Try this:
import pandas as pd
import datetime
df = pd.read_csv("my.csv")
df.insert(0, 'Date', datetime.datetime.today().strftime('%Y-%m-%d'))
df.to_csv("my_withDate.csv", index=False)
PS: Read the docs
答案2
得分: 0
这是您要查找的内容吗?
import pandas as pd
import datetime
df = pd.read_csv("file.csv")
df['Date'] = datetime.datetime.today().strftime('%Y-%m-%d')
df.to_csv("new_file.csv", index=False)
英文:
Is this what you are looking for?
import pandas as pd
import datetime
df = pd.read_csv("file.csv")
df['Date'] = datetime.datetime.today().strftime('%Y-%m-%d')
df.to_csv("new_file.csv", index=False)
答案3
得分: 0
根据我理解,最终目标是将数据写入CSV文件。实现这个目标的一种方法是首先打开一个文件以读取数据,然后打开另一个文件以写入数据,接着将标题行写入新文件,并在标题行前加上列名'Date,',然后迭代数据行,在每一行前加上日期(需要使用Python版本3.6及以上,因为使用了f-strings):
import datetime
with open('columns.csv', 'r') as out, open('out.csv', 'w') as into:
headers = 'Date,' + next(out)
print(headers, end='', file=into)
for row in out:
print(f'{datetime.datetime.today().date()}, {row}', end='', file=into)
英文:
As far as I undestand ultimate goal is to write data to csv. One option to do that is to open first file for reading data, second for writing data then write header row into new file prepending it with column name 'Date,' and then iterate over data rows prepending them with date (requires 3.6 <= Python as uses f-strings):
import datetime
with open('columns.csv', 'r') as out, open('out.csv', 'w') as into:
headers = 'Date,' + next(out)
print(headers, end='', file=into)
for row in out:
print(f'{datetime.datetime.today().date()}, {row}', end='', file=into)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论