简体   繁体   English

保存带有日期变量扩展名的文件

[英]Saving a file with a date variable extension

My aim is to check a text file for a size (> 0 bytes) and if True, copy the file to another directory. 我的目的是检查文本文件的大小(> 0字节),如果为True,则将文件复制到另一个目录。 What i would like to add is a date to the file by generating a date variable. 我想添加的是通过生成日期变量将日期添加到文件中。 The part i am unable to figure out is how to add the date variable when I copy the file. 我无法弄清的部分是复制文件时如何添加日期变量。 The below code works fine except adding the variable called yesterday to the filename. 下面的代码可以正常工作,除了将yesterday调用的变量添加到文件名中。 Any ideas on how do perform this last part of the code ? 关于如何执行代码的最后部分的任何想法?

import os
import shutil
import datetime

# a variable called yesterday will be generated (yesterdays date)
today = datetime.date.today()
one_day = datetime.timedelta(days=1)
yesterday = today - one_day

# Check if file is True

file_path = r"C:\temp\Missing_File.txt"
if os.stat(file_path).st_size > 0:
    shutil.copy("C:/temp/Missing_File.txt", "C:/temp2/Missing_File.txt")

Use str.format() : 使用str.format()

shutil.copy("C:/temp/Missing_File.txt", "C:/temp2/Missing_File_{}.txt".format(yesterday))

If you have Python 3.6+, another option is to use an f-string : 如果您使用的是Python 3.6+,则另一个选择是使用f字符串

shutil.copy("C:/temp/Missing_File.txt", f"C:/temp2/Missing_File_{yesterday}.txt")

You can also customize stringification of a date object by specifying a format string in the placeholder, eg: 您还可以自定义字串一的date指定的占位符,如格式字符串对象:

>>> import datetime
>>> yesterday = datetime.date.today() - datetime.timedelta(days=1)
>>> "C:/temp2/Missing_File_{:%A}.txt".format(yesterday)
'C:/temp2/Missing_File_Sunday.txt'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM