我有一个文件夹结构,其中有我的根文件夹,然后在该根文件夹中还有其他3个文件夹。
Root_folder
|
|- Folder1
|- file1.txt
|- file2.txt
|- Folder2
|- file3.txt
|- file4.jpg
|- Folder3
|- file5.txt
我正在尝试让我的脚本在三个文件夹中的每个文件夹中运行,并计算每个文件夹中文件的使用期限。这个工作正常,但是我的zip功能出现问题。
我收到一条错误消息,说没有这样的文件或目录。如果在致电print(file)
之前添加zip_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'
答案 0 :(得分:1)
os.listdir()
仅在文件夹中提供文件名,但要打开文件,您需要完整路径-folder/filename
,因此必须在{p>中使用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()
中,如果您在return
循环内使用for
,则它在第一个文件之后退出。您可以跳过return
。但是您可以将列表作为参数def zip_file(files_to_zip):