我想删除并替换一个名称超过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
答案 0 :(得分:0)
由于os.path.getctime处理对inode的更改,这可能是由于inode的分配方式所致。
在大多数文件系统上,如果先删除文件然后再创建另一个文件,则通过删除前一个文件而释放的inode将分配给新文件(前提是在删除和新文件创建操作之间未创建新文件)。 / p>
touch temp.txt
stat -c%I temp.txt
970724
rm temp.txt
touch temp.txt
stat -c%I temp.txt
970724
rm temp.txt
touch temp1.txt
stat -c%I temp1.txt
970724
touch temp.txt
stat -c%I temp.txt
970727
当您执行os.path.getctime时,它将为您提供关于文件最后一次元数据更改的时间。 os.path.getmtime提供有关文件内容更改信息的信息,例如读和写。
注意:由于文件许可权的更改会更改元信息,因此并非始终都能始终获得确切的文件创建日期和时间。