递归列出文件夹中的文件并解压缩zip文件

时间:2016-11-21 16:26:10

标签: python list recursion zip

我试图以递归方式列出文件夹中的所有文件(包括子文件夹)并解压缩zip文件夹。我是怎么做的:

def scan(real_path):
    matches = []
    for root, dirnames, filenames in walk(real_path):
        for filename in fil(filenames, '*'):
            matches.append(path.join(root, filename))
    return matches


def unzip(destination, path):
    z = ZipFile(path, mode = "r")
    for archive in z.namelist():
        content = z.read(archive)
        archive = open("%s/%s" % (destination, archive), "w")
        archive.write(content)
        z.close()


def startup_files(starting_over = False):
    print "STARTING FILES AGAIN..." if starting_over else \
          "STARTING FILES..."

    x = scan(folder)
    print "Files found in folder:"
    print x
    for archive in x:
        archive = Archive.details(archive)
        print "READING:", archive.full_path
        if archive.extension == ".ZIP":
            unpack_zip(archive)
            remove(archive.full_path)
            startup_files(True)

这导致了这个奇怪的错误。我正在使用2个文件1.zip2.ZIP测试脚本,我在哪个文件中有这个文件:SFPDB001.GBK

输出结果为:

迭代一:好的

STARTING FILES...
Files found in folder:
['arp\\_input\\backups\\1.zip', 'arp\\_input\\backups\\2.ZIP']
READING: C:\Users\G1745 IRON\Development\LL\ARP\arp\_input\backups\1.zip

迭代二:好的

STARTING FILES AGAIN...
Files found in folder:
['arp\\_input\\backups\\2.ZIP', 'arp\\_input\\backups\\SFPDB001.GBK']
READING: C:\Users\G1745 IRON\Development\LL\ARP\arp\_input\backups\2.ZIP

迭代三:错误:扫描功能是在文件夹中找到正确的文件,但迭代试图到达不可用的文件。

STARTING FILES AGAIN...
Files found in folder:
['arp\\_input\\backups\\SFPDB001.GBK']
READING: C:\Users\G1745 IRON\Development\LL\ARP\arp\_input\backups\SFPDB001.GBK
READING: C:\Users\G1745 IRON\Development\LL\ARP\arp\_input\backups\SFPDB001.GBK
READING: C:\Users\G1745 IRON\Development\LL\ARP\arp\_input\backups\2.ZIP

C:\Users\G1745 IRON\Development\LL\ARP\arp\_input\backups\2.ZIP

Traceback (most recent call last):
  File "arp\__main__.py", line 22, in <module>
    main()
  File "arp\__main__.py", line 18, in main
    ARP(p.parse_args()).run()
  File "C:\Users\G1745 IRON\Development\LL\ARP\arp\arp.py", line 26, in run
    self.startup_files()
  File "C:\Users\G1745 IRON\Development\LL\ARP\arp\arp.py", line 46, in startup_files
    self.unpack_zip(archive)
  File "C:\Users\G1745 IRON\Development\LL\ARP\arp\arp.py", line 62, in unpack_zip
    Zip.unzip(self.folder, archive.full_path)
  File "C:\Users\G1745 IRON\Development\LL\ARP\arp\zip.py", line 17, in unzip
    z = ZipFile(path, mode = "r")
  File "C:\Python25\lib\zipfile.py", line 339, in __init__
    self.fp = open(file, modeDict[mode])
IOError: [Errno 2] No such file or directory: 'C:\\Users\\G1745 IRON\\Development\\LL\\ARP\\arp\\_input\\backups\\2.ZIP'

我不知道为什么会这样......我有一个JS背景,我现在开始使用python,所以我不知道我是否应该做点什么。

OBS:我使用的是Python v2.5,因为它是遗留代码。

1 个答案:

答案 0 :(得分:0)

我发现了错误,当我从循环中调用它时,我应该返回startup_files

return self.startup_files(True)

这就是全部。