在 PYTHON 中为文件添加时间戳 [英] Adding timestamp to a file in PYTHON

查看:155
本文介绍了在 PYTHON 中为文件添加时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can able to rename a file without any problem/error using os.rename().

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

But the moment I tried to rename a file with timestamp adding to it, it throws win3 error or win123 error, tried all combinations but no luck, Could anyone help.

成功运行代码:

#!/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

推荐答案

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

Your timestamp format has colons in it, which are not allowed in Windows filenames. See this answer on that subject:

如何获得Windows 中文件名中带有冒号的文件?

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

If you change your timestamp format to something like:

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

它应该可以工作.

这篇关于在 PYTHON 中为文件添加时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆