【问题标题】:Adding timestamp to a file in PYTHON在 PYTHON 中为文件添加时间戳
【发布时间】:2018-09-19 00:53:36
【问题描述】:

我可以使用 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

【问题讨论】:

    标签: python-3.x timestamp pycharm


    【解决方案1】:

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

    改变

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

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

    你可以重命名你的文件

    【讨论】:

      【解决方案2】:

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

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

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

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

      它应该可以工作。

      【讨论】:

        猜你喜欢
        • 2018-04-29
        • 1970-01-01
        • 2017-07-07
        • 2016-09-21
        • 1970-01-01
        • 2020-01-03
        • 2016-10-23
        • 2011-11-21
        • 2014-07-13
        相关资源
        最近更新 更多