Zipping files in multiple directories / FileNotFoundError: [Errno 2] No such file or directory

Zipping files in multiple directories / FileNotFoundError: [Errno 2] No such file or directory

我有一个文件夹结构,其中有我的根文件夹,然后根文件夹中有 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() for folder

 time_created = os.stat(folder).st_ctime

也许你的意思是 file 而不是 folder

 time_created = os.stat(file).st_ctime

In zip_file() 如果你在 for-loop 中使用 return 那么它会在第一个文件后退出。您可以跳过 return。但是您可以将列表作为参数发送 def zip_file(files_to_zip):