【发布时间】:2020-12-07 11:35:43
【问题描述】:
我有以下结构:
Folder1
ZZ-20201201-XX.zip
Folder2
XX-20201201-XX.zip
XX-20201202-XX.zip
Folder3
YY-20201201-XX.zip
YY-20201202-XX.zip
使用下面的代码,我创建了 Folder1, Folder2 和 Folder3 的对应项,并直接解压缩这 3 个文件夹中的压缩文件。所以我收到了这个:
Folder1
ZZ-.txt
Folder2
XX-.txt
Folder3
YY.txt
如您所见,文件一旦解压缩就会丢失日期,因此如果文件夹包含 2 个压缩文件,它们将获得相同的名称,因此文件将被重写。现在我想在文件解压缩后将压缩文件的日期添加到文件中。我该怎么做?
import fnmatch
pattern = '*.zip'
for root, dirs, files in os.walk(my_files):
for filename in fnmatch.filter(files, pattern):
path = os.path.join(root, filename)
date_zipped_file = re.search('-(.\d+)-', filename).group(1) #<-- this is the date of the zipped files and I want this to be included in the name of the unzipped files once they get unzipped.
# Store the new directory so that it can be recreated
new_dir = os.path.normpath(os.path.join(os.path.relpath(path, start=my_files), ".."))
# Join your target directory with newly created directory
new = os.path.join(counter_part, new_dir)
# Create those folders, works even with nested folders
if (not os.path.exists(new)):
os.makedirs(new)
zipfile.ZipFile(path).extractall(new)
我想要的结果:
Folder1
ZZ-20201201.txt
Folder2
XX-20201201.txt
XX-20201202.txt
Folder3
YY-20201201.txt
XX-20201202.txt
【问题讨论】: