在Python中处理目录和路径

1. glob

有时我们需要匹配某个目录下的某些文件, 可能需要用到*, ?等符号, 这是可以考虑使用glob模块. glob模块支持*, ? []三种匹配, 分别代表匹配多个任意字符, 匹配一个任意字符以及区间(range).

假设目录Users/kemaswill/Work/Learning

下面有以下文件:

file1.txtfile2.txtfile3.txtfile11.txtfile12.txt

#*匹配多个任意字符>>> import glob>>> for path in glob.glob('/Users/kemaswill/Work/Learning/file*.txt'):...     print path.../Users/kemaswill/Work/Learning/file1.txt/Users/kemaswill/Work/Learning/file11.txt /Users/kemaswill/Work/Learning/file12.txt /Users/kemaswill/Work/Learning/file2.txt /Users/kemaswill/Work/Learning/file3.txt #?匹配一个任意字符 >>> import glob >>> for path in glob.glob('/Users/kemaswill/Work/Learning/file?.txt'): ... print path ... /Users/kemaswill/Work/Learning/file1.txt /Users/kemaswill/Work/Learning/file2.txt /Users/kemaswill/Work/Learning/file3.txt #[]表示区间,[1-2]表示1和2 >>> import glob >>> for path in glob.glob('/Users/kemaswill/Work/Learning/file[1-2].txt'): ... print path ... /Users/kemaswill/Work/Learning/file1.txt /Users/kemaswill/Work/Learning/file2.txt

如果想匹配?或*本身, 使用[?], [*]如果文件名以.开头, 则使用?和*是匹配不到的.glob模块还有一个iglob函数, 返回的是一个迭代器而不是一个列表.

2. os

os模块有很多和目录以及路径相关的函数

2.1 用~表示用户目录

如果想像在shell中一样使用~代表用户目录, 可以使用os.path.expanduser函数:

#展示用户目录(/user/kemaswill)下的所有txt后缀的文件>>> import os>>> import glob>>> for path in glob.glob(os.path.expanduser("~") + '/*.txt'):...     print path/user/kemaswill/file1.txt/user/kemaswill/file2.txt

2.2 连接目录名和文件名

os.path.join函数可以把目录名和文件名连接起来, 连接的字符为os.sep, 在UNIX系统上为/, ?在Windows上为\\.

#展示用户目录(/user/kemaswill)下的所有txt后缀的文件>>> import os>>> import glob>>> for path in glob.glob(os.path.join(os.path.expanduser("~"), '*.txt')):...     print path/user/kemaswill/file1.txt/user/kemaswill/file2.txt

2.3 切分文件路径和文件名

os.path.split函数可以把一个文件的绝对路径切分为目录的路径和文件名:

import os>>> os.path.split('/user/jwpan/file1.txt')('/user/jwpan', 'file1.txt')

os.path.splitex函数可以把文件名的后缀和后缀前的文件名(略饶, :()切分开

import os>>> os.path.splitext('file1.txt')('file', 'txt')

2.4 遍历目录

使用os.path.listdir来遍历一个目录, 使用os.path.isfile和os.path.isdir来判断一个路径是目录还是文件:

>>> import os>>> dirname = '/user/jwpan'>>> for f in os.path.listdir(dirname):...     print os.path.join(dirname, f).../user/jwpan/file1.txt/user/jwpan/file2.txt

参考文献:

[1]. Python 2.7.6 Document: 10.7 glob

[2]. Dive into Python: 6.5 Working with directories

在Python中处理目录和路径

相关文章:

你感兴趣的文章:

标签云: