python pandas to csv file save, not override

1357 views python
5

I read a csv file and did some modification of the data repeatedly. 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".

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. 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.

answered question

3 Answers

7

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')

posted this
7

According to pandas.DataFrame.to_csv documentation, date_format affects only the Format string for datetime object inside the dataframe, not the filename.

You can use datetime and format to achieve what you need, i.e.:

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')

posted this
6

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)

posted this

Have an answer?

JD

Please login first before posting an answer.