Python 压缩多个目录中的文件/FileNotFoundError:[Errno 2]没有这样的文件或目录
我有一个文件夹结构,其中我有我的根文件夹,然后在根文件夹中有3个其他文件夹Python 压缩多个目录中的文件/FileNotFoundError:[Errno 2]没有这样的文件或目录,python,gzip,Python,Gzip,我有一个文件夹结构,其中我有我的根文件夹,然后在根文件夹中有3个其他文件夹 Root_folder | |- Folder1 |- file1.txt |- file2.txt |- Folder2 |- file3.txt |- file4.jpg |- Folder3 |- file5.txt 我试图让我的脚本在这三个文件夹中运行,并计算每个文件夹中文件的年龄。这很好,但是我的zip函数有问题 我得到一个错误,说没有这样的文件或目录。如果在调用zip\u文件
Root_folder
|
|- Folder1
|- file1.txt
|- file2.txt
|- Folder2
|- file3.txt
|- file4.jpg
|- Folder3
|- file5.txt
我试图让我的脚本在这三个文件夹中运行,并计算每个文件夹中文件的年龄。这很好,但是我的zip函数有问题
我得到一个错误,说没有这样的文件或目录。如果在调用zip\u文件之前添加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")
os.listdir()
只提供文件夹中的文件名,但要打开文件,您需要完整路径-文件夹/文件名
,因此您必须在中使用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()
文件夹的
time_created = os.stat(folder).st_ctime
time_created = os.stat(file).st_ctime
也许你指的是文件
而不是文件夹
time_created = os.stat(folder).st_ctime
time_created = os.stat(file).st_ctime
在zip_file()
中,如果在for
-循环中使用return
,则它会在第一个文件之后退出。您可以跳过返回。但您可以将列表作为参数def zip\u文件(files\u to\u zip)发送:
这是否回答了您的问题?这是对一个目录中的文件进行迭代。我想迭代多个目录中的多个文件。如果您想要连接路径,请将结果分配给变量,不要使用str()
,因为您创建了错误的路径fullpath=os.path.join(root\u目录,文件夹)
始终将完整的错误消息(从单词“Traceback”开始)作为文本(不是屏幕截图)放入问题中(不是注释). 还有其他有用的信息。对于这个错误,我只能说:要读取不同文件夹中的文件,必须创建完整路径-fullpath=os.path.join(根目录,文件夹)
,然后打开(完整路径)