如何检查文件是否是python中的目录或常规文件? [重复]

本文翻译自:how to check if a file is a directory or regular file in python? [duplicate]

Possible Duplicate: 可能重复:
How to identify whether a file is normal file or directory using python 如何使用python识别文件是普通文件还是目录

How do you check if a path is a directory or file in python? 如何检查路径是否是python中的目录或文件?


#1楼

参考:https://stackoom.com/question/DRi2/如何检查文件是否是python中的目录或常规文件-重复


#2楼

Many of the Python directory functions are in the os.path module . 许多Python目录函数都在os.path模块中

import os
os.path.isdir(d)

#3楼

os.path.isfile("bob.txt") # Does bob.txt exist?  Is it a file, or a directory?
os.path.isdir("bob")

#4楼

use os.path.isdir(path) 使用os.path.isdir(path)

more info here http://docs.python.org/library/os.path.html 更多信息请访问http://docs.python.org/library/os.path.html


#5楼

An educational example from the stat documentation: 统计文档中的教育示例:

import os, sys
from stat import *

def walktree(top, callback):
    '''recursively descend the directory tree rooted at top,
       calling the callback function for each regular file'''

    for f in os.listdir(top):
        pathname = os.path.join(top, f)
        mode = os.stat(pathname)[ST_MODE]
        if S_ISDIR(mode):
            # It's a directory, recurse into it
            walktree(pathname, callback)
        elif S_ISREG(mode):
            # It's a file, call the callback function
            callback(pathname)
        else:
            # Unknown file type, print a message
            print 'Skipping %s' % pathname

def visitfile(file):
    print 'visiting', file

if __name__ == '__main__':
    walktree(sys.argv[1], visitfile)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值