【问题标题】:Distinguishing between files and directories in Python在 Python 中区分文件和目录
【发布时间】:2018-01-29 17:48:34
【问题描述】:

我试图只获取文件夹中的文件,不包括任何其他目录。但下面的脚本正在将所有文件和文件夹移动到另一个目录。

while True:
    # Go through each of the directories
    for mylist in dirlist:
        check_dir = mylist[0]
        callback = mylist[1]

        # get the list of files in the directory
        filelist = os.listdir(check_dir)
        for this_file in filelist:
            if ((this_file == ".") or (this_file == "..") or (this_file == "donecsvfiles") or (this_file == "doneringofiles")):
                print "Skipping self and parent"
                continue

            full_filename = "%s/%s"%(check_dir, this_file)

【问题讨论】:

  • 您是否还希望将子目录中的文件(如果有)包含在列表中?
  • 不,只是文件

标签: python file directory


【解决方案1】:

os.path中,有有用的isdir()isfile()函数:

>>> import os
>>> 
>>> os.path.isfile('demo.py')
True
>>> os.path.isdir('demo.py')
False
>>> os.path.isfile('__pycache__')
False
>>> os.path.isdir('__pycache__')

另外,您可以使用os.walk()os.scandir() 自动将两者分开:

for root, dirs, files in os.walk('python/Lib/email'):
    print('Searching:', root)
    print('All directories', dirs)
    print('All files:', files)
    print('----------------------')

【讨论】:

    【解决方案2】:

    Python 3.5+ 提供了一个生成器,它通常比列表推导和循环更有效。您可以通过for i in arr 进行遍历,通过next(arr) 进行迭代,或者通过list(arr) 获取完整列表。

    import os
    
    arr = os.scandir('H:\public\python')  # returns a generator
    

    【讨论】:

      【解决方案3】:

      您可以使用os.path 中的isfile 来检查路径是否为文件。此代码为您提供文件夹中的文件列表:

      from os.path import isfile, join
      from os import listdir
      
      folder = 'path//to//folder'
      onlyfiles = [f for f in listdir(folder) if isfile(join(folder, f))]
      

      【讨论】:

        【解决方案4】:

        几乎直接取自docs

        import os
        
        with os.scandir('.') as it:
            for entry in it:
                if entry.is_file():
                    print(entry)
        

        【讨论】:

          猜你喜欢
          • 2012-04-13
          • 1970-01-01
          • 2021-07-18
          • 1970-01-01
          • 2013-05-01
          • 2010-09-17
          • 2012-02-19
          • 1970-01-01
          相关资源
          最近更新 更多