拉链拉到折叠处

2024-04-25 01:15:46 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是文件结构的样子

music_folder
    album1.zip (below are contents inside of zip)
        song1.mp3
        song2.mp3
        song3.mp3
    album2.zip (below are contents inside of zip)
        song12.mp3
        song14.mp3
        song16.mp3

我想将两个压缩的相册解压到一个名为cache的目录中,并且我想要相同的结构。这就是我想要的样子:

cache
    album1 (this is a normal unzipped folder)
        song1.mp3
        song2.mp3
        song3.mp3
    album2 (this is a normal unzipped folder)
        song12.mp3
        song14.mp3
        song16.mp3

但出于某种原因,对于album1,文件是直接在cache目录中提取的,而不是cache/album1。你知道吗

这就是它的样子,我不想要这个:

cache
    song1.mp3
    song2.mp3
    song3.mp3
    album2 (this is a normal unzipped folder)
        song12.mp3
        song14.mp3
        song16.mp3

下面是我的代码:

for zipped_album in os.listdir('music_folder'):
    zip_ref = ZipFile('music_folder/' + zipped_album, 'r')
    zip_ref.extractall('cache')
    zip_ref.close()

你知道为什么这些文件没有被提取到chachealbum1文件夹中吗?它适用于album2


Tags: 文件cachemusicfolderzipmp3样子song1
1条回答
网友
1楼 · 发布于 2024-04-25 01:15:46

Zip文件可以包含(相对)路径名,而不仅仅是文件名。你知道吗

因此,album2.zip的内容实际上很可能是:

  • 专辑2/song1.mp3
  • 专辑2/song2.mp3
  • 专辑2/song3.mp3

…但是album1.zip只是:

  • 歌曲1.mp3
  • 歌曲2.mp3
  • 歌曲3.mp3

为了测试这一点,您可以在shell中执行unzip -l album1.zipunzip -l album2.zip。你知道吗


这实际上是一个问题,人们一直有,只要他们一直在分享zipfiles。您通常希望在路径中包含album2,但有时会丢失它。您不希望强制添加它并以album2/album2/song1.mp3结束,但也不希望不添加它而只以song1.mp3结束在顶级目录中。你知道吗

现在大多数GUI工具使用的解决方案(我认为它可以追溯到古老的Stuffit Expander)是:

  • Iterate all of the zip entries并查看路径名是否都以相同的目录开头。你知道吗
  • 如果是,请按原样解压。你知道吗
  • 否则,创建一个与zipfile同名的目录(减去.zip),然后将它们解压到该目录中。你知道吗

一个棘手的问题是zipfile路径可以是Windows或POSIX格式,它们可以是绝对路径或UNC路径,甚至可以是以..开头的路径,并且将这些路径转换为可用路径的逻辑不仅仅是一个行程,尽管并不困难。因此,您必须决定要使代码完全通用到什么程度。你知道吗

相关问题 更多 >