python - 区分Python中的文件和目录

标签 python file directory

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

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)

最佳答案

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('----------------------')

关于python - 区分Python中的文件和目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48507133/

相关文章:

python - 如何在没有字符串连接的情况下在 Python 中重复字符?

python - "python setup.py install"不创建入口 pip

python - 如果变量不在列表中 == False 返回空列表

c# - 改变输出流的位置

javascript - 从 Node 中的 JSON 文件中删除字段

Python 交叉表多个变量或行;人口统计表

file - Grails - 从 Quartz 作业和过滤器记录日志

windows - 如何使用 CMD 或 Powershell 打开 'This PC'?

java - 如何监听并获取文件目录中的文件列表?

c# - 从目录中删除只读属性