制作备份文件+附加日期时间+移动文件(如果文件存在),PYTHON

ttygqcqt  于 4个月前  发布在  Python
关注(0)|答案(3)|浏览(79)

我有一些工作的碎片,但我正在努力把它们放在一起。
我想取一个文件,将其移动到备份文件夹,从该文件中获取日期时间,并将其附加到文件名/将文件名更改为文件名+日期时间。
这一部分以我想要的格式获取日期时间。(打印行是正确格式化的日期时间,但我不需要打印这一行)

Filepath = "C:\\SyncWork\\ACE\\Files\\ESAL_P\\ESAL_P.txt"
    modifiedTime = os.path.getmtime(Filepath) 
    firstFile = os.path.getmtime(Filepath)

    print (datetime.fromtimestamp(modifiedTime).strftime("%b-%d-%y-%H:%M:%S"))

字符串
此部分将重命名/移动文件(但缺少日期时间)

prevName = 'c:\\syncwork\\ace\\files\\ESAL_P\\ESAL_P.txt'
    newName = 'c:\\syncwork\\ace\\files\\ESAL_P\\Backup\\ESAL_P.txt'

    os.rename(prevName, newName)


如何将打印行的格式转换为字符串,并将其追加到newName行的末尾?

我的问题得到回答后我的最终代码看起来像这样:

Filepath = "C:\\SyncWork\\ACE\\Files\\ESAL_P\\ESAL_P.txt"
modifiedTime = os.path.getmtime(Filepath) 


timestamp = datetime.fromtimestamp(modifiedTime).strftime("%b-%d-%Y_%H.%M.%S")

prevName = 'c:\\SyncWork\\ACE\\Files\\ESAL_P\\ESAL_P.txt'
newName = 'c:\\SyncWork\\ACE\\Files\\ESAL_P\\Backup\\ESAL_P' 

os.rename(prevName, newName+"_"+timestamp + ".txt")
print(newName)

nqwrtyyt

nqwrtyyt1#

我刚刚在一个名为“temp”的文件上测试了以下内容,该文件已更改为“temp_Sep-15-14-08:42:57”

FilePath = 'temp' # replace the temp with your file path/name
modifiedTime = os.path.getmtime(FilePath) 

timeStamp =  datetime.datetime.fromtimestamp(modifiedTime).strftime("%b-%d-%y-%H:%M:%S")
os.rename(FilePath,FilePath+"_"+timeStamp)

字符串

fdbelqdn

fdbelqdn2#

这应该可以做到:

timestamp = (datetime.fromtimestamp(modifiedTime).strftime("%b-%d-%y-%H:%M:%S"))
newName = 'c:\\syncwork\\ace\\files\\ESAL_P\\Backup\\ESAL_P.txt.' + timestamp

字符串

z9zf31ra

z9zf31ra3#

基于您已经拥有的避免重复代码和增加可用性的解决方案,我建议使用path库:

import os
from pathlib import Path

# create the filename as a path
filename = Path("C:\\SyncWork\\ACE\\Files\\ESAL_P\\ESAL_P.txt")

# derive the name of the backup folder from the origin and create it if necessary
target_directory = filename.parent / 'Backup'
if not target_directory.is_dir():
    print(f'Creating directory {target_directory}')
    os.mkdir(target_directory)

# this is the original part creating the timestamp
modified_time = os.path.getmtime(filename)
timestamp = datetime.fromtimestamp(modified_time).strftime("%b-%d-%Y_%H.%M.%S")

# build the target name from the original name, the timestamp and the original extension
target_file = target_directory / f'{filename.stem}_{timestamp}{filename.suffix}'
print(target_file)
os.rename(filename, target_file)

字符串
这种方法的优点是适用于任何扩展,并且更安全。它看起来更长,但是如果你去掉注解,它就和你的一样长了:

filename = Path("C:\\SyncWork\\ACE\\Files\\ESAL_P\\ESAL_P.txt")
target_directory = filename.parent / 'Backup'

modified_time = os.path.getmtime(filename)
timestamp = datetime.fromtimestamp(modified_time).strftime("%b-%d-%Y_%H.%M.%S")

target_file = target_directory / f'{filename.stem}_{timestamp}{filename.suffix}'
print(target_file)
os.rename(filename, target_file)


希望你觉得有用。

相关问题