Python 3.x 在PYTHON中向文件添加时间戳

Python 3.x 在PYTHON中向文件添加时间戳,python-3.x,timestamp,pycharm,Python 3.x,Timestamp,Pycharm,我可以使用os.rename()重命名文件,而不会出现任何问题/错误 但是,当我试图重命名一个添加了时间戳的文件时,它抛出了win3错误或win123错误,尝试了所有的组合,但没有运气,任何人都能帮上忙 已成功运行代码: #!/usr/bin/python import datetime import os import shutil import json import re maindir = "F:/Protocols/" os.chdir(maindir) maindir = os.

我可以使用os.rename()重命名文件,而不会出现任何问题/错误

但是,当我试图重命名一个添加了时间戳的文件时,它抛出了win3错误或win123错误,尝试了所有的组合,但没有运气,任何人都能帮上忙

已成功运行代码:

#!/usr/bin/python
import datetime
import os
import shutil
import json
import re


maindir = "F:/Protocols/"
os.chdir(maindir)
maindir = os.getcwd()
print("Working Directory : "+maindir)
path_4_all_iter = os.path.abspath("all_iteration.txt")
now = datetime.datetime.now()
timestamp = str(now.strftime("%Y%m%d_%H:%M:%S"))
print(type(timestamp))
archive_name = "all_iteration_"+timestamp+".txt"
print(archive_name)
print(os.getcwd())
if os.path.exists("all_iteration.txt"):
    print("File Exists")
    os.rename(path_4_all_iter, "F:/Protocols/archive/archive.txt")
    print(os.listdir("F:/Protocols/archive/"))

print(os.path.abspath("all_iteration.txt"))
日志:

错误日志:

E:\python.exe C:/Users/SPAR/PycharmProjects/Sample/debug.py
Traceback (most recent call last):
Working Directory : F:\Protocols
<class 'str'>
  File "C:/Users/SPAR/PycharmProjects/Sample/debug.py", line 22, in <module>
all_iteration_20180409_20:31:16.txt
F:\Protocols
    os.rename(path_4_all_iter, "F:/Protocols/archive/"+archive_name)
File Exists
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'F:\\Protocols\\all_iteration.txt' -> 'F:/Protocols/archive/all_iteration_20180409_20:31:16.txt'

Process finished with exit code 1
E:\python.exe C:/Users/SPAR/PycharmProjects/Sample/debug.py
回溯(最近一次呼叫最后一次):
工作目录:F:\Protocols
文件“C:/Users/SPAR/PycharmProjects/Sample/debug.py”,第22行,在
所有迭代\u 20180409\u 20:31:16.txt
F:\协议
重命名(路径4所有文件,“F:/Protocols/archive/”+归档文件名)
文件存在
OSError:[WinError 123]文件名、目录名或卷标语法不正确:“F:\\Protocols\\all\u iteration.txt”->“F:/Protocols/archive/all\u iteration\u 20180409\u 20:31:16.txt”
进程已完成,退出代码为1

时间戳格式中有冒号,这在Windows文件名中是不允许的。请参阅关于该主题的以下答案:

如果将时间戳格式更改为以下格式:

timestamp = str(now.strftime("%Y%m%d_%H-%M-%S"))

它应该可以工作。

您不能将
作为文件名的一部分

改变

timestamp = str(now.strftime("%Y%m%d_%H:%M:%S"))

您可以重命名您的文件

timestamp = str(now.strftime("%Y%m%d_%H-%M-%S"))
timestamp = str(now.strftime("%Y%m%d_%H:%M:%S"))
timestamp = str(now.strftime("%Y%m%d_%H%M%S"))