我有一个文件夹结构,其中我有我的根文件夹,然后在根文件夹中有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)
顺便说一句:在下一个循环中,您一次又一次地得到
stat()
forfolder
也许你的意思是
file
,而不是folder
在
zip_file()
中,如果在for
-循环中使用return
,那么它将在第一个文件之后退出。你可以跳过return
。但您可以将列表作为参数def zip_file(files_to_zip):
发送相关问题 更多 >
编程相关推荐