简体   繁体   English

python pandas到csv文件保存,不覆盖

[英]python pandas to csv file save, not override

I read a csv file and did some modification of the data repeatedly. 我读了一个csv文件并重复修改了一些数据。 And I tried to save the csv with the file name " naver_news_YYYY_MM_DD_HH_MM.csv . However, If I run this program repeatedly, but I can find only last csv file with " naver_news.csv ". 我试图用文件名“ naver_news_YYYY_MM_DD_HH_MM.csv来保存csv。但是,如果我重复运行这个程序,但我只能找到带有” naver_news.csv “的最后一个csv文件。

This is the code as followed. 这是以下代码。

df.to_csv("C:/Users/Administrator/PycharmProjects/news/naver_news.csv", date_format='%Y-%m-%d', index = False, sep=',', encoding='ms949')

Then I can only find one " naver_news.csv " file in my computer. 然后我只能在我的电脑中找到一个“ naver_news.csv ”文件。 The result file nave that I am expecting is as followed. 我期待的结果文件是如下。

naver_news_2018_09_17_10_42.csv
naver_news_2018_09_17_11_42.csv
naver_news_2018_09_17_12_42.csv
naver_news_2018_09_17_13_42.csv 

Please let me know to save csv file with current current time. 请告知我用当前时间保存csv文件。

You'll need to insert the timestamp label into the filename yourself. 您需要自己将时间戳标签插入文件名。

ts = pd.to_datetime('today').strftime('%Y_%m_%d_%H_%M')
filename = f"C:/Users/Administrator/PycharmProjects/news/naver_news_{ts}.csv"
# filename = "C:/Users/Administrator/PycharmProjects/news/naver_news_{}.csv".format(ts) 
df.to_csv(filename, index=False, encoding='ms949')

You can create a function to get timestamp whenever you want, 您可以创建一个函数来随时获取时间戳,

from datetime import datetime


def get_date_time(fmt='%Y_%m_%d_%H_%M_%S'):
    date_stamp = datetime.now().strftime(fmt)
    print("%s " % date_stamp)
    return date_stamp


file_name = "C:/Users/Administrator/PycharmProjects/news/naver_news_{}.csv".format(get_date_time())
print(file_name)

According to pandas.DataFrame.to_csv documentation, date_format affects only the Format string for datetime object inside the dataframe , not the filename, but you can use something like: pandas.DataFrame.to_csv文档, date_format 影响内部DateTime对象格式字符串 dataframe ,而不是文件名,但你可以使用这样的:

from datetime import datetime
fn = "C:/Users/Administrator/PycharmProjects/news/naver_news_{}.csv".format(format(datetime.now(), '%Y_%m_%d_%H_%M'))
df.to_csv(fn, index = False, sep=',', encoding='ms949')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM