关于目录、文件的一些操作

 

怎样使用 Python 来判断一个路径是否存在判断一个路径是文件还是目录

判断一个路径是否存在

可以判断一个文件或目录(文件夹)是否存在

    import os.path
    os.path.exists(path);

判断一个文件是否存在

    import os.path
    os.path.isfile(path);

判断一个目录(文件夹)是否存在

    import os.path
    os.path.isdir(path);

判断一个路径是文件还是目录(文件夹)

  • 方法一
    import os.path
    os.path.isdir(path);
    # 返回 True 表示是目录(文件夹)

  • 方法二
    import os.path
    os.path.isfile(path);
    # 返回 True 表示是文件

 

经常会遇到在目录下过滤特定后缀名的文件的需求。自己总结下面两个方法:

第一种方法、比较常规:代码如下

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

#!/usr/bin/python

 

defendWith(s,*endstring):

        array=map(s.endswith,endstring)

        ifTrue in array:

                returnTrue

        else:

                returnFalse

 

if__name__ =='__main__':

        importos

        s=os.listdir('/root/')

        f_file=[]

        fori ins:

                ifendWith(i,'.txt','.py'):

                        printi,

 

执行结果如下:

 

 

1

第二种方法:个人比较倾向这种方法,这种方法可定制性更强,代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<preclass="brush:py;">#!/usr/bin/python

defendWith(*endstring):

        ends=endstring

        defrun(s):

                f=map(s.endswith,ends)

                ifTrue in f: returns

        returnrun

 

if__name__ =='__main__':

        importos

 

        list_file=os.listdir('/root')

        a=endWith('.txt','.py')

        f_file=filter(a,list_file)

        fori inf_file: printi,</pre>

 

执行结果如下:

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值