代码之家  ›  专栏  ›  技术社区  ›  Chicken Sandwich No Pickles

Python列表理解错误澄清[关闭]

  •  0
  • Chicken Sandwich No Pickles  · 技术社区  · 5 年前

    这是我的密码:

    subfolders = [ f.path for f in os.scandir(x) if f.is_dir() ]
    

    subfolders = []
    
    x = "c:\\Users\\my_account\\AppData\\Program\\Cache"
    
    for f in os.scandir(x):
         if f.isdir():
              print(f.x)
    

    运行此代码时,会收到以下错误消息:

    Traceback (most recent call last):
      File "<pyshell#210>", line 2, in <module>
        if f.is_dir():
    AttributeError: 'nt.DirEntry' object has no attribute 'isdir'
    

    我做错什么了?

    编辑#1 :

    for f in os.scandir(x):
         print(f)
    
    <DirEntry 'filename.dat'>
    <DirEntry 'AnotherFile.dat'>
    

    也许这跟这事有关?

    1 回复  |  直到 5 年前
        1
  •  1
  •   markmnl    5 年前

    f 类型为: nt.DirEntry 而且没有一个 isdir() 功能,但它确实有 is_dir() 用那个!

    for f in os.scandir(x):
         if f.is_dir():
              print(f.x)
    

    要获得路径列表,通常还需要考虑 glob 哪个更人性化:

    import glob
    
    subfolders = [path for path in glob.glob(f"{x}/**/*", recursive=True) if os.path.isdir(path)]
    
    推荐文章