2

所以,这是我的小程序。它应该打印给定目录中的所有文件+每个子目录中的所有文件。

import os

def listFiles(directory):
    dirList = os.listdir(directory)
    printList = []
    for i in dirList:
        i = os.path.join(directory,i)
      #  print(i)
        if os.path.isdir(i):
            printList[len(dirList):] = listFiles(i)
        else:
            printList.append(i)
    return printList

directory = 'C:\Python32\Lib'
listFiles(directory)
a = listFiles(directory)

for i in a:
    print(i)

有什么问题: os.path.isdir(i) 无法正常工作 - 例如,如果我尝试

os.path.isfile('C:\Python32\Lib\concurrent\futures\process.py')
os.path.exists('C:\Python32\Lib\concurrent\futures\process.py')
os.path.isdir('C:\Python32\Lib\concurrent\futures')

我总是得到 False 而不是 True (它适用于某些子目录)。如果我取消注释 print(i) 它会打印所有内容,但它也会打印目录 - 我只想打印文件。我应该怎么办?

4

1 回答 1

2

printList[len(dirList):] = listFiles(i)将在每个循环中覆盖值。

例如,如果您在其中的所有条目dirList都是目录,那么您最终会在printList遍历每个子目录时从中删除条目:

>>> printList = []
>>> len_dirlist = 2  # make up a size
>>> printList[len_dirlist:] = ['foo', 'bar', 'baz'] # subdir 1 read
>>> printList
['foo', 'bar', 'baz']
>>> printList[len_dirlist:] = ['spam', 'ham', 'eggs'] # subdir 2 read
>>> printList
['foo', 'bar', 'spam', 'ham', 'eggs']  # Wait, where did 'baz' go?

.extend()在将项目添加到列表末尾时,您希望使用它。

请注意,在 Windows 上,您不必使用反斜杠作为路径分隔符,最好使用正斜杠,因为它们在 Python 字符串中没有特殊含义:

'C:/Python32/Lib/concurrent/futures/process.py'

或者,使用r'' 原始字符串文字来消除反斜杠被解释为字符转义的机会:

r'C:\Python32\Lib\concurrent\futures\process.py'
于 2012-09-22T20:38:10.920 回答