所以,这是我的小程序。它应该打印给定目录中的所有文件+每个子目录中的所有文件。
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) 它会很好地打印所有内容,但它也会打印目录 - 我只想打印文件。我该怎么办?
最佳答案
您的 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''
raw 字符串文字来消除反斜杠被解释为字符转义的可能性:
r'C:\Python32\Lib\concurrent\futures\process.py'
关于Python:os.path.isdir/isfile/exists 不起作用,当它们应该返回 True 时返回 False,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12547070/