您的位置:首页 > 编程语言 > Python开发

python文件、目录及路径操作

2014-08-31 22:14 941 查看
http://blog.csdn.net/pipisorry/article/details/47907589

os.path — Common pathname manipulations

都是和路径指定的文件,目录,和路径字符串有关系的函数

os.path.isdir(name) 判断name是不是一个目录,name不是目录就返回false

os.path.isfile(name) 判断name是不是一个文件,不存在name也返回false
os.path.islink(name) 判断nama是不是一个链接文件

os.path.exists(name) 判断是否存在文件或目录name

os.path.getsize(name) 获得文件大小,如果name是目录返回0L

os.path.abspath(name) 获得绝对路径

os.path.normpath(path) 规范path字符串形式

os.path.split(name) 分割文件名与目录(事实上,如果你完全使用目录,它也会将最后一个目录作为文件名而分离,同时它不会判断文件或目录是否存在)
os.path.splitext() 分离文件名与扩展名

os.path.join(path,name) 连接目录与文件名或目录

os.path.basename(path) 返回文件名

os.path.dirname(path) 返回文件路径
分解
basename(path)

Return the base name of pathname path. This is the second half of the pair returned by split(path).

Note that the result of this function is different from the Unix basename program; where basename for ’/foo/bar/’ returns ’bar’, the basename() function returns an empty string (”).

dirname(path)

Return the directory name of pathname path. This is the first half of the pair returned by split(path).
os.path.split()函数

返回一个路径的目录名和文件名。
>>> os.path.split('/home/shirley/myself/code/icbc.txt')  
('/home/shirley/myself/code', 'icbc.txt')

Note:path.split()中目录参数对结果的影响
print(path.split(r'E:\mine\java_workspace\AMC_master\Data\Input\corpus_NP'))

返回('E:\\mine\\java_workspace\\AMC_master\\Data\\Input', 'corpus_NP'),而
print(path.split(r'E:\mine\java_workspace\AMC_master\Data\Input\corpus_NP/'))

返回('E:\\mine\\java_workspace\\AMC_master\\Data\\Input\\corpus_NP', '')
splitext(path)

Split the pathname path into a pair (root, ext) such that root + ext == path, and ext is empty or begins with a period and contains at most one period. Leading periods on the basename are ignored;

splitext(’.cshrc’) returns (’.cshrc’, ”). Changed in version 2.6: Earlier versions could produce an empty root when the only period was the first character.

join(path1, [path2, [...]])

Join one or more path components intelligently. If any component is an absolute path, all previous components (on Windows, including the previous drive letter, if there was one) are thrown away, and joining continues. The return value is the
concatenation of path1, and optionally path2, etc., with exactly one directory separator (os.sep) inserted between components, unless path2 is empty. Note that onWindows, since there is a current directory for each drive,os.path.join("c:", "foo") represents
a path relative to the current directory on drive C: (c:foo), not c:\foo.

[https://docs.python.org/3/library/os.html]
[The Python Library Reference Release2.6 - 11.1]
[python系统模块sys、os及应用]
http://blog.csdn.net/pipisorry

os — Files and Directories
getcwd()

Return a string representing the current working directory. Availability: Unix, Windows.

listdir(path)

Return a list containing the names of the entries in the directory. The list is in arbitrary order. It does not include the special entries ’.’ and ’..’ even if they are present in the directory. Availability: Unix,Windows. Changed in version
2.3: OnWindows NT/2k/XP and Unix, if path is a Unicode object, the result will be a list of Unicode objects.

makedirs(path, [mode])

Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory. Throws an error exception if the leaf directory already exists or cannot be created. The default mode is
0777 (octal). On some systems, mode is ignored. Where it is used, the current umask value is first masked out.

Note: makedirs() will become confused if the path elements to create include os.pardir. New in version 1.5.2.Changed in version 2.3: This function now handles UNC paths correctly.

walk(top, [topdown=True, [onerror=None, [followlinks=False]]])

Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames,filenames).......

[The Python Library Reference Release2.6 - 16.1.4]

[python系统模块sys、os及应用]
皮皮Blog

路径、文件名相关库

fnmatch 实现shell风格模式匹配特定字符

fnmatch.fnmatch(names, pattern):测试name是否匹配pattern,返回true/false。下面的例子列出了当前目录中的所有py文件:

>>>import fnmatch

>>>import os

>>>for file in os.listdir('.'):

... if fnmatch.fnmatch(file, '*.py'):

... print file

...

allfile.py

list_get.py

test.py
如果操作系统是大小写不敏感的,则在fnmatch.fnmatch()中所有的参数将被统一格式为所有大写或所有小写。

fnmatch.fnmatchcase( names, pattern):与平台无关的大小写敏感的fnmatch.fnmatch
fnmatch.filter(names, pattern):实现列表特殊字符的过滤或筛选,返回符合匹配模式的字符列表,例:

>>> files=['tags', 'readme.txt', 'allfile.py', 'test.py']

>>> fnmatch.filter(files, '*.py')

['allfile.py', 'test.py']

>>> fnmatch.filter(files, '[tx]')

[]

>>> fnmatch.filter(files, '[tx]*')

['tags', 'test.py']

>>> fnmatch.filter(files, '*')

['tags', 'readme.txt', 'test.py']

>>> fnmatch.filter(files, '**')

['tags', 'readme.txt', 'test.py']

>>> fnmatch.filter(files, '?[a]*')

['tags']
注意: [seq] 匹配单个seq中的任意单个字符

fnmatch.translate(pattern):翻译模式, fnmatch将这种全局模式转换成一个正则式, 然后使用re模块来比较名字和模式。 translate() 函数是一个公共API用于将全局模式转换成正则式。

>>>import fnmatch

>>> pattern='*.py'

>>>print fnmatch.translate(pattern)

.*\.py\Z(?ms)

unix shell风格匹配方式

*表示匹配任何单个或多个字符
?表示匹配单个字符
[seq] 匹配单个seq中的任意单个字符
[!seq]匹配单个不是seq中的任意单个字符

from:http://blog.csdn.net/pipisorry/article/details/47907589
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: