在PYTHON中为文件添加时间戳

时间:2018-04-09 15:03:32

标签: 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.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
Working Directory : F:\Protocols
<class 'str'>
all_iteration_20180409_20:25:51.txt
F:\Protocols
File Exists
['archive.txt']
F:\Protocols\all_iteration.txt

Process finished with exit code 0

错误代码:

    print(os.getcwd())
if os.path.exists("all_iteration.txt"):
    print("File Exists")
    os.rename(path_4_all_iter, "F:/Protocols/archive/"+archive_name)
    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

2 个答案:

答案 0 :(得分:1)

您的时间戳格式中包含冒号,Windows文件名中不允许使用冒号。看到关于该主题的答案:

How to get a file in Windows with a colon in the filename?

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

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

它应该有用。

答案 1 :(得分:1)

您无法将:作为文件名的一部分

更改

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

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

您可以重命名文件