【问题标题】:Python: os.path.isdir /isfile /exists not working, returning False when they should return TruePython:os.path.isdir /isfile /exists 不起作用,当它们应该返回 True 时返回 False
【发布时间】:2025-12-28 14:50:06
【问题描述】:

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

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) 它会打印所有内容,但它也会打印目录 - 我只想打印文件。我该怎么办?

【问题讨论】:

  • 如果我使用原始字符串(我将 r 放在字符串之前),它可以在 shell 中工作,但是如何在程序/变量中进行这项工作?
  • 您想使用.extend() 而不是复杂的切片分配。
  • 你有看过os.walk()吗?它会为您完成所有这些工作。
  • 是的,我知道 os.walk() 但我想像以前那样做。无论如何 .extend() 解决了这个问题!谢谢。
  • 对于硬编码的任何路径,都需要注意反斜杠。 \f 是换页符,可能不是您想要的。您应该使用双反斜杠 C:\\Python32\\... 或使用原始字符串 r'C:\Python32\...'

标签: python


【解决方案1】:

您的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'

【讨论】:

    最近更新 更多