os walk目录返回字符串文字以进行解压缩

时间:2018-03-24 01:57:25

标签: string python-3.x data-structures zipfile os.walk

问题出现在字符串变量试图被zipfile.Zipfile(变量)读取的地方。回调文件不存在。这是因为它为每个文件夹添加了一个额外的\。我尝试了几件事来尝试将字符串变成文字但是当我这样做时会打印出一个额外的\\\。我甚至尝试将其作为文字,但正如我所期望的那样重复同样的事情返回\\\\\。任何见解都会非常感激!!! 代码结构如下,这里是回调函数

Traceback (most recent call last):
  File "C:\Users\Yume\Desktop\Walk a Dir Unzip and copy to.py", line 17, in <module>
    z = zipfile.ZipFile(zf, 'r')
  File "C:\Users\Yume\AppData\Local\Programs\Python\Python36-32\lib\zipfile.py", line 1090, in __init__
    self.fp = io.open(file, filemode)
FileNotFoundError: [Errno 2] No such file or directory: "C:\\Users\\Yume\\AppData\\Roaming\\

Traceback (most recent call last):
  File "C:\Users\Yume\Desktop\Walk a Dir Unzip and copy to.py", line 17, in <module> z = zipfile.ZipFile(rzf, 'r')
  File "C:\Users\Yume\AppData\Local\Programs\Python\Python36-32\lib\zipfile.py", line 1090, in __init__
    self.fp = io.open(file, filemode)
OSError: [Errno 22] Invalid argument: '"C:\\\\Users\\\\Yume\\\\AppData\\\\Roaming\\\\


   z = zipfile.ZipFile(rrzf, 'r')
  File "C:\Users\Yume\AppData\Local\Programs\Python\Python36-32\lib\zipfile.py", line 1090, in __init__
    self.fp = io.open(file, filemode)
OSError: [Errno 22] Invalid argument: '\'"C:\\\\\\\\Users\\\\\\\\Yume\\\\\\\\AppData\\\\\\\\Roaming\\\\\\\

CODE:

import os
import re
from shutil import copyfile
import zipfile
import rarfile

isRar = re.compile('.+\\.rar')
isZip = re.compile('.+\\.zip')
for folderName, subfolders, filenames in os.walk(r'C:\Users\Yume\AppData'):

    if isZip.match(str(filenames)):
    zf =  folderName+ str(subfolders)+str(filenames)
    rzf = '%r'%zf
    z = zipfile.ZipFile(zf)
    z.extractall(r'C:\Users\Yume')
    z.close()                   
    if isRar.match(str(filenames)):
    rf = folderName+ str(subfolders)+str(filenames)
    rrf = "%r"%rf
    r = rarfile.RarFile(rf)
    r.extractall(r'C:\Users\Yume')  
    r.close()

1 个答案:

答案 0 :(得分:0)

通过在os walk创建的文件列表中运行for循环来纠正我的问题。我清理了我的代码,这是一个工作程序,它遍历一个目录,找到一个压缩的.zip或.rar并将其提取到指定的目的地。

import os
import zipfile
import rarfile
import unrar

isRar = re.compile('.*\\.rar')
isZip = re.compile('.*\\.zip')
for dirpath, dirnames, filenames in os.walk(r'C:\Users\'):
  for file in filenames:
    if isZip.match(file):
        zf = os.path.join(dirpath, file)
        z= zipfile.ZipFile(zf)
        z.extractall(r'C:\Users\Unzipped')
        z.close()
    if isRar.match(file):
        rf = os.path.join(dirpath, file)
        r = rarfile.RarFile(rf)
        r.extractall(r'C:\Users\Unzipped')
        r.close()