在 csv 中保存数据帧时将时间戳添加到文件名
Add Timestamp to file name during saving Data Frame in csv
当我将文件保存为 .csv 时,我想在其旁边添加创建该文件时的时间戳。我试过这个,但没用:
df.to_csv('File_name_{}.csv'.format(pd.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
它给我这个输出:
OSError: [Errno 22] Invalid argument: 'File_name_2021-05-12 16:20:23.csv'
我该如何纠正?
Windows 上的文件名中不允许使用冒号,因此您可以使用无冒号行,它应该可以正常工作:
df.to_csv('File_name_{}.csv'.format(pd.datetime.now().strftime("%Y-%m-%d %H%M%S")))
根据微软 Documentation:
Use any character in the current code page for a name, including
Unicode characters and characters in the extended character set
(128–255), except for the following:
The following reserved characters:
- < (less than)
- > (greater than)
- : (colon)
- " (double quote)
- / (forward slash)
- \ (backslash)
- | (vertical bar or pipe)
- ? (question mark)
- * (asterisk)
Integer value zero, sometimes referred to as the ASCII NUL character.
Characters whose integer representations are in the range from 1 through 31, except for alternate data streams where these characters
are allowed. For more information about file streams, see File
Streams.
Any other character that the target file system does not allow.
一个简单的解决方法是执行以下操作:
df.to_csv('File_name_{}.csv'.format(pd.datetime.now().strftime("%Y-%m-%d %Hh%Mm%Ss")))
当我将文件保存为 .csv 时,我想在其旁边添加创建该文件时的时间戳。我试过这个,但没用:
df.to_csv('File_name_{}.csv'.format(pd.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
它给我这个输出:
OSError: [Errno 22] Invalid argument: 'File_name_2021-05-12 16:20:23.csv'
我该如何纠正?
Windows 上的文件名中不允许使用冒号,因此您可以使用无冒号行,它应该可以正常工作:
df.to_csv('File_name_{}.csv'.format(pd.datetime.now().strftime("%Y-%m-%d %H%M%S")))
根据微软 Documentation:
Use any character in the current code page for a name, including Unicode characters and characters in the extended character set (128–255), except for the following:
The following reserved characters:
- < (less than)
- > (greater than)
- : (colon)
- " (double quote)
- / (forward slash)
- \ (backslash)
- | (vertical bar or pipe)
- ? (question mark)
- * (asterisk)
Integer value zero, sometimes referred to as the ASCII NUL character.
Characters whose integer representations are in the range from 1 through 31, except for alternate data streams where these characters are allowed. For more information about file streams, see File Streams.
Any other character that the target file system does not allow.
一个简单的解决方法是执行以下操作:
df.to_csv('File_name_{}.csv'.format(pd.datetime.now().strftime("%Y-%m-%d %Hh%Mm%Ss")))