使用 Python 存档文件(最新文件除外)
Archiving Files Using Python Apart from Latest File
我正在尝试将现有文件与 Python 或 FME 中最新修改的文件分开。我已经设法让它指向我可以 python 获取最新修改文件的位置,但是关于如何归档文件夹中除上次修改文件之外的所有文件的任何想法?
谢谢
您可以使用这段代码解决您的问题:
import glob
import os
import zipfile
files_dir = r'C:\Users\..\files' # here should be path to directory with your files
files = glob.glob(files_dir + '\*')
# find all files that located in specified directory
files_modify_dt = [os.path.getmtime(file) for file in files]
# take files except last modified file
files_to_zip = [file for _, file in sorted(zip(files_modify_dt, files))][:-1]
# zip of selected files
with zipfile.ZipFile(os.path.join(files_dir, 'archive.zip'), 'w', zipfile.ZIP_DEFLATED) as zip_obj:
for file in files_to_zip:
zip_obj.write(file, os.path.basename(file))
os.remove(file)
我正在尝试将现有文件与 Python 或 FME 中最新修改的文件分开。我已经设法让它指向我可以 python 获取最新修改文件的位置,但是关于如何归档文件夹中除上次修改文件之外的所有文件的任何想法?
谢谢
您可以使用这段代码解决您的问题:
import glob
import os
import zipfile
files_dir = r'C:\Users\..\files' # here should be path to directory with your files
files = glob.glob(files_dir + '\*')
# find all files that located in specified directory
files_modify_dt = [os.path.getmtime(file) for file in files]
# take files except last modified file
files_to_zip = [file for _, file in sorted(zip(files_modify_dt, files))][:-1]
# zip of selected files
with zipfile.ZipFile(os.path.join(files_dir, 'archive.zip'), 'w', zipfile.ZIP_DEFLATED) as zip_obj:
for file in files_to_zip:
zip_obj.write(file, os.path.basename(file))
os.remove(file)