When I specify the file name with the to_csv method of the pandas module and output it, it is overwritten and the old file disappears.
A method to output individually and prevent overwriting by including the date and time of execution in the file name.
① datetime module ② now method ③ strftime method ④ format function
code
import datetime as dt
now = dt.datetime.now()
time = now.strftime('%Y%m%d-%H%M%S')
df.to_csv('~/desktop/output_{}.csv'.format(time), index=False, encoding='utf_8_sig')
A separate file is generated each time you run it.
datetime now method
import datetime as dt
now = dt.datetime.now()
now
#output
# datetime.datetime(2020, 3, 27, 19, 16, 41, 332644)
About datetime [here](# https://qiita.com/yuta-38/items/eb2ad47e8a25bde21c6c)
datetime strftime method
time = now.strftime('%Y%m%d-%H%M%S')
time
#output
#'20200327-191641'
-Detailed explanation of strftime method is here
・ For the types of specifiers (% Y,% d, etc.), click here (https://qiita.com/yuta-38/items/ba6dce967ede22e37c60#%E6%97%A5%E4%BB%98%E3% 81% AE% E6% 8C% 87% E5% AE% 9A% E5% AD% 90% E4% B8% 80% E8% A6% A7)
format function
time = now.strftime('%Y%m%d-%H%M%S')
'output_{}.csv'.format(time)
#output
# 'output_20200327-193206.csv'
Click here for details of the format function [https://qiita.com/yuta-38/items/9a93eea10ccc7ac2c8ad)
csv file output
df.to_csv('~/desktop/output_{}.csv'.format(time), index=False, encoding='utf_8_sig')
For the to_csv method, click here (https://qiita.com/yuta-38/items/4ee7518b1e82e60822f8)
Recommended Posts