python操作文件目录

# 查看当前目录的绝对路径:

1 >>> os.path.abspath('.')
2 /Users/NaCl/Documents/GitHub

#同样的道理,要拆分路径时,也不要直接去拆字符串,而要通过os.path.split()函数,这样可以把一个路径拆分为两部分,后一部分总是最后级别的目录或文件名:

1 >>>os.path.splitext('/Users/NaCl/Documents/GitHub/iotest.txt')
2 ('/Users/NaCl/Documents/GitHub/iotest', '.txt') 注意返回值是一个tupple

#os.path.splitext()可以非常方便的得到文件扩展名:

1 for x in os.listdir('/Users/NaCl/Documents/GitHub'):
2 if os.path.isfile(x) and os.path.splitext(x)[1]=='.py':
3 print x
//
os.path.isfile(x):如果x是一个文件
os.path.splitext(x)[1]:如果X的扩展名是.py
1 结果:
2 IO_Python.py
3 section2.py
4 section3.py
5 section4.py
6 section7.py
7 simple MLP with keras.py

#最后看看如何利用Python的特性来过滤文件。比如我们要列出某个目录下的所有目录,只需要一行代码:

1 >>> [x for x in os.listdir('/Users/NaCl') if os.path.isdir(x)]
2 ['.lein', '.local', '.m2', '.npm', '.ssh', '.Trash', '.vim', 'Applications', 'Desktop', ...]
原文地址:https://www.cnblogs.com/anyview/p/5041401.html