如果超过 6 天,我想删除并替换同名的 Excel 文件。os.path.getctime(file_path)但是,当我根据 [ ][1]评估文件的年龄时,getctime删除并替换它后该值不会改变。
我不确定是否使用getmtime或getatime会起作用,因为我将在此期间修改文件。
import os #check existing excel file stats
import time #find creation date of file
import openpyxl #excel module
import sys #to collect sys args from command line
def establish_wb():
file_path = r'C:\Users\cj9250\Documents\this_weeks_blue_stakes.xlsx'
if os.path.exists(file_path) == False: #if excel file does not exist
wb = openpyxl.Workbook()
wb.save(file_path)#create it
current_time = time.time()
creation_time = os.path.getctime(file_path) #when file was created
file_age = (current_time - creation_time)/86400 #number of days since
print(file_age)
if file_age > 6: #if older than 6 days, replace the file
os.remove(file_path)
wb = openpyxl.Workbook()
wb.save(file_path)#create file
print('new one')
else:#if younger than 6 days use existing one
wb = openpyxl.load_workbook(file_path)
print('old one')
return wb
[1]: https://docs.python.org/2/library/os.path.html
我最终通过将文档创建时间存储在随机单元格中来解决这个问题。
import os #check existing excel file stats
import time #find creation date of file
import openpyxl #excel module
import sys #to collect sys args from command line
def establish_wb():
file_name = 'this_weeks_blue_stakes.xlsx'
file_path = 'C:\\Users\\cj9250\\Documents\\' + file_name
if os.path.exists(file_path) == False: #if excel file does not exist
wb = openpyxl.Workbook()
wb.active['a49'] = time.time() #record creation time
wb.save(file_path)#create it
return wb #end function?
else:#if it already exists, give wb a value for upcoming var assignments
wb = openpyxl.load_workbook(file_path)
print('a file existed')
current_time = time.time()
creation_time = wb.active['a49'].value #when file was created
file_age = (current_time - creation_time)/86400 #number of days since creation
print('this is the age ' + str(file_age))
if file_age > .0005: #if older than 6 days, replace the file
os.remove(file_path) #delete the file
wb = openpyxl.Workbook()
wb.active['a49'] = time.time()
wb.save(file_path)#create file
print('made a new new one')
else:#if younger than 6 days use existing one
wb = openpyxl.load_workbook(file_path)
print('used the old one')
return wb