概述
涉及到文件和文件夹的操作的一般有三个模块
- os
- os.path
- shutil
os.path
os.path 模块,顾名思义就是针对于系统的文件路径啊,判断是否为文件啊等等行为做出处理的模块。
os.path.abspath(path)
返回当前绝对路径+path参数的字符
1 | >>> os.path.abspath('.') |
os.path.basename(path)
返回路径下面的文件名的字符串。(这个文件路径可能不存在)
1 | >>> os.path.basename('/user/johnw/test.txt') |
os.path.commonpath([path1,path2])
接受一个序列,得到两个字符串中相同的文件路径(一定要是路径字符串)
1 | >>> os.path.commonpath(['/user/johnw/log.txt','/user/johnw/logs/test.txt']) |
os.path.commonprefix([path1,path2])
顾名思义,接受路径字符的序列,比较前缀
1 | >>> os.path.commonprefix(['/usr/lib', '/usr/local/lib']) |
os.path.dirname(path)
返回路径字符串中的关于文件夹的路径
1 | >>> os.path.dirname('/usr/local/src/') |
os.path.exists(path)
判断文件路径是否真实存在
1 | >>> os.path.exists('/usr/local/src') |
os.path.expanduser(path)
把path中包含的""和"user"转换成用户目录
1 | >>> os.path.expanduser('~') |
os.path.expandvars(path)
根据环境变量,替换路径存在的$name 和 ${name} 的值
1 | >>> os.path.expandvars('$PYENV_ROOT') |
os.path.getatime(path)
os.path.getmtime(path)
os.path.getctime(path)
1 | 文件的 Access time,atime 是在读取文件或者执行文件时更改的任何对inode的访问都会使此处改变。 |
os.path.getsize(path)
得到文件的大小。 以bytes为单位。如果不存在或者路径错误,返回OSError
1 | [21:31:34] xxx ➜ ~» ls -hl demo.py |
os.path.isabs(path)
如果是绝对路径,返回True
1 | >>> os.path.isabs('/user') |
os.path.isfile(path)
os.path.isdir(path)
os.path.islink(path)
os.path.ismount(path)
顾名思义,判断语句.会先判断这个路径字符是否真实存在,如果不存在,返回False
1 | >>> os.path.isfile('/user/text.txt') |
os.path.join(path)
将字符拼接成合适的字符路径
1 | >>> os.path.join('usr','src') |
os.path.normcase(path)
os.path.normpath(path)
格式化字符路径,使之符合当前系统格式
1 | >>> os.path.normcase('/User/local') |
os.path.realpath(path)
返回字符路径的真实路径
1 | >>> os.path.realpath('.') |
os.path.relpath(path)
返回相对路径
1 | >>> os.path.relpath('/Users/xxx') |
os.path.samefile(path1,path2)
如果两个文件名都是指向同一个文件的话,返回True,this is determined by the device number and i-node number
os.path.sameopenfile(fp1,fp2)
os.path.split(path)
切割成 路径 , 文件名
1 | >>> os.path.split('/usr/local/test.txt') |
os.path.splitext(path)
切割成路径 , 后缀名
1 | >>> os.path.splitext('/usr/local/test.txt') |