我有一个文件夹结构,其中有我的根文件夹,然后在根文件夹中有其他 3 个文件夹。
Root_folder
|
|- Folder1
|- file1.txt
|- file2.txt
|- Folder2
|- file3.txt
|- file4.jpg
|- Folder3
|- file5.txt
我正在尝试让我的脚本运行三个文件夹中的每一个,并计算每个文件夹中文件的年龄。这工作正常,但是我的zip功能遇到了问题。
我收到一个错误,说没有这样的文件或目录。如果我在调用zip_file
之前添加一个print(file)
,我将得到file4.jpg
import os
import time
import gzip
root_directory = ('C:/Users/Path/Desktop/To_Files/')
folders = ['inbox', 'outbox']
retention_age_days = {
'.txt':100,
'.jpg':200,
}
zip_extension = ('.jpg')
files_to_zip = []
def zip_file():
for file in files_to_zip:
fp = open(file, "rb")
data = fp.read()
bindata = bytearray(data)
with gzip.open(file + ".gz", "wb") as f:
f.write(bindata)
return
for folder in folders:
os.path.join(str((root_directory, folder)))
files = [f for f in os.listdir(folder) if f.endswith(tuple(retention_age_days.keys()))]
for file in files:
time_created = os.stat(folder).st_ctime
now = time.time()
file_age_seconds = now - time_created # file age in seconds
file_age_days = (now - time_created) / 86400 # 1 day = 86400 seconds
ending = "." + file.split(".")[-1]
if ending in retention_age_days:
# deletion statments should go in here, replacing print statements
if file_age_days > retention_age_days[ending]:
print(file, file_age_days, "file is older than retention days")
elif file_age_days <= retention_age_days[ending] and file.endswith(zip_extension):
files_to_zip.append(file)
zip_file()
elif file_age_days <= retention_age_days[ending]:
print(file, file_age_days, "file is not older than retention days")
我不确定发生了什么。当我print(os.getcwd())
即使在for folder in folders
循环中时,我也不断得到一个输出,说我的cwd是(C:/Users/Path/Desktop/To_Files/'('''
任何帮助修复我的zip功能将不胜感激!
编辑:完整回溯:
Traceback (most recent call last):
File "C:/Users/Path/Desktop/To_Files/file.py", line 50, in <module>
zip_file()
File "C:/Users/Path/Desktop/To_Files/file.py", line 24, in zip_file
fp = open(file, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'jpg_test.jpg'
os.listdir()
只在文件夹中给出文件名,但要打开文件,您需要完整路径 -folder/filename
所以你必须os.path.join(folder, f)
在
extensions = tuple(retention_age_days.keys())
files = [os.path.join(folder, f)
for f in os.listdir(folder)
if f.endswith(extensions)]
顺便说一句:在下一个循环中,你会一次又一次地stat()
folder
time_created = os.stat(folder).st_ctime
也许你的意思是file
而不是folder
time_created = os.stat(file).st_ctime
zip_file()
如果您在 -loop 中使用return
for
那么它会在第一个文件后退出。你可以跳过return
.但是您可以将列表作为参数发送def zip_file(files_to_zip):