【问题标题】:why Python zipfile doesn't unzip these files?为什么 Python zipfile 不解压缩这些文件?
【发布时间】:2019-07-20 01:48:50
【问题描述】:

我有一些代码适用于某些文件,但不适用于其他文件。我很困惑!我拿了同一个文件,用不同的名字复制了十次来模拟一个生产案例。

文件将位于两个不同的路径中。 path_one 有效,但 path_two 无效。

import zipfile

path_one = "/tmp/my_files_one"
path_two = "/tmp/my_files_two"

for file in os.listdir(path_one):
    print("xx", file)
#    if zipfile.is_zipfile(file):
#        print("in here")
    with zipfile.ZipFile(file, 'r') as zipo:
        zipo.extractall(path=path_one)

但如果我使用 path_two,我会收到此错误:

xx file_two.zip
Traceback (most recent call last):
  File "./this_script.py", line 95, in <module>
    with zipfile.ZipFile(file, 'r') as zipo:
  File "/usr/lib64/python3.4/zipfile.py", line 923, in __init__
    self.fp = io.open(file, modeDict[mode])
FileNotFoundError: [Errno 2] No such file or directory: 'file_two.zip'

文件肯定在路径中。我取消了 is_zipfile 部分的注释,因为它不是真的,即使其他文件也是如此。

为什么?

【问题讨论】:

  • "但是如果我使用 path_two...." 你能粘贴你用于 path_two 的确切代码吗?通常最好将损坏的代码提供给 Stack Overflow。

标签: python-3.x zip


【解决方案1】:

问题似乎是使用相对路径,并且您从 /tmp/my_files_one 运行命令,以便成为当前工作目录。

尝试使用 os.path.join(dir, file) 获取文件的绝对路径

import zipfile

path_one = "/tmp/my_files_one"
path_two = "/tmp/my_files_two"

for file in os.listdir(path_two):
    file = os.path.join(path_two, file)
    print("xx", file)
    if zipfile.is_zipfile(file):
        print("in here")
    with zipfile.ZipFile(file, 'r') as zipo:
        zipo.extractall(path=path_two)

【讨论】:

  • 是的,os.path.join 现在可以工作了。虽然我发誓我的脚本在上面的一些文件上工作。诡异的。无论如何,谢谢!
  • 当您运行脚本时,您的脚本应该适用于当前工作目录中的所有文件。并且不适用于不在当前工作目录中的文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多