python----------路径操作

路径操作

3.4版本之前

os.path模块

from os import path
p = path.join('/etc','sysconfig','network')
print(type(p),p)
print(path.exists(p))
print(path.split(p))
print(path.dirname(p),path.basename(p))
print(path.abspath(''),path.abspath('.'))
print(path.splitdrive('o:/tmp/test'))
p1 = path.abspath(__file__)
print(p1)
whle p1 != path.firname(p1):
    dirname = path.dirname(p1)
    print(dirname)
    p1 = dirname

3,4版本开始
建议使用pathlib模块,提供Path对象来操作,包括目录和文件

pathlib模块

frompathlib import Path
目录操作
初始化
p = Path() #当前目录, Path(),Path(’,’),path(’’)
p = Path(‘a’,‘b’.‘c/d’) #
p = Path(’/etc’) # 根下的etc目录
路径拼接和分解

  • 操作符/
    Path对象/Path对象
    Path对象 /字符串 或者 字符串 / Path对象
  • 分解
    parts属性,可以返回路径中的每一个部分
  • joinpath
    joinpath(*other)连接多个字符串到path对象中
p = Path()
p = p / 'a'
p1 = 'b' / p
p2 = Path('c')
p3 = p2 / p1
print(p3.parts)
p3.joinpath('etc','init.d',Path('httpd'))
  • 获取路径
    str 获取路径字符串
    bytes 获取路径字符串的bytes
p = Path('/a/b/c/d')
print(p.parent.parent)
for x in p.parents:
    print(x)
  • 目录组成部分
    name.steam,suffix,suffixes.with)suffix(suffix).with_name(name)
    name 目录中的最后一个部分
    suffix 目录中最后一个部分的扩展名
    stem 目录中最后一个部分,没有后缀
    name = stem + suffix

suffix 返回多个扩展名列表
with_suffix(suffix)有扩展名则替换,无则补充扩展名
with_name(name)替换目录最后一个部分并返回一个新的路径

from pathlib import Path
p = Path('/python/mysqlinstall/mysql.tar.gz')
print(p.name)
print(p.suffix)
print(p.suffixes)
print(p.stem)
print(p.with_name('mysql-5.tgz'))
print(p.with_suffix('.png'))
p = Path('README')
print(p.with_suffix('.txt'))
  • 全局方法
    cwd()返回当前工作目录
    home()返回当前家目录
  • 判断方法
    exists()目录或文件是否存在
    is_dir()是否是目录,目录存在返回True
    is_file()是否是普通文件,文件存在返回True
    is_symlink()是否是软连接
    ls_socket()是否是socket文件
    is_block_device()是否是块设备
    is_char_device()是否是字符设备
    is_absolute()是否是绝对路径
  • 绝对路径
    resolve()非Windows,返回一个新的路径,这个新路径就是当前Path对象的绝对路径,如果是软连接则直接被破解析.

absolute()获取绝对路径
redir()删除空目录.没有提供判断目录为空的方法
touch(mode=0o666,exist_ok=True)创建一个文件
as_uri()将路径返回成URI,例如’file:///etc/passwd’

mkdir(mode=0o777,parents=Flase,exist_ok=Flase)
parents.是否创建父目录,True等同于mkdir -p.Flase时,父目录不存在则抛出 FIleNotFoundError
exise_ok参数,在3.5版本加入.False时路径存在,抛出FileExistsError;True时, FileExistsError被忽略

iterdir()
迭代当前目录,不递归

p = Path()
p /= 'a/b/c/d'
p.exists()  #检测当前目录是否存在
p.mkdir()   #FileNotFoundError
p,mkdir(parents=True)
p.exists()   # True
p.mkdir(parents=True)
p.mkdir(parents=True,exist_ok=True)
p /= 'redme.txt'
p.parent.rmdir()        # 删除的不是空目录
p.paret.exists()        # False '/a/b/c'
p.mkdir()      #FileNotFoundError
p.mkdir(parent=True) # 成功

# 遍历,并判断文件类型,如果目录是否可以判断其是否为空目录
for x in p.parents[len(p.parents)-1].iterdir():
    print(x,end='\t')
    if x.is_dir():
        flag = False
        for _ inx.iterdir():
            flag = True
            break
        print('dir','Not Empyt' if flag else 'Empyt',sep = '\t')
    elif s.is_file():
        print(file)
    else:
        print('other file')
  • 通配符
    glob(pattern)通配给定的模式
    rglob(pattern)统配给定的模式,递归目录
    都返回一个生成器
    ?代表一个字符
    *表示任意个字符
    [abc]或[a-z]表示一个字符
list(p.glob('test*'))   #返回当前目录对象下的test开头的文件
list(p.glob('**/*.py')) #递归所有目录,等同rglob
list(p.glob('**/*'))

g = p.rglob('*.pt') #生成器,递归
nest(g)
list(p.rglob('*.???')) # 匹配扩展名为3个字符的文件
list(p1.rglob('[a-z]*.???')) # 匹配字母开头的且扩展名时三个字符的文件
  • 匹配
    match(pattern)
    模式匹配,成功返回True
Path('a/b.py').match('*.py')  # True
Path('a/b/c.py').match('b/*.py')  # True
Path('a/b/c.py').match('a/*.py')  # False
Path('a/b/c.py').match('a/*/*,py')  # True
Path('a/b/c.py').match('a/**/*,py')  # True
Path('a/b/c.py').match('**/*.py')   # True

stat()相当于stat命令
lstat()同stat(),但如果是符号链接,则显示符号链接本身的文件信息

# ln -s test t

from pathlib import Path
p = Path('test')
p.stat()
p1 = Path('t')
p1.stat()
p1.lstat()
  • 文件操作
Path.open(mode='r',fuddering=-1,encode=None,errors=None,newline=None)
# 使用方法类似内建函数open,返回一个文件对象

# 3.5增加的问函数
Path.read_bytes()
# 以'rb'读取路径对应文件,并返回二进制流.看源码

Path.read_text(encoding=None,error=None)
# 以'rt'方式读取路径对应文件,返回文本

Path.write_bytes(date)
# 以'wb'方式写入数据到路径对应文件

path.write_text(date,encoding=None,errors=None)
以'wt'方式写入字符串到路径对应文件

from pathlib import Path

p = Path('my_binary_file')
p.write_bytes(b'Binary file contents')
p.read_bytes() # b'Binary file contents

p = Path('my_text_file')
p.write_text('text file contents')
p.read_text()

with p.open() as f:
    print(f.read(5))

os模块

  • 操作系统平台
属性或方法结果
os.namewindows是nt,linus是posix
os.uname()*nix支持
sys.platformwindows显示win32,linux显示linux

os.listdir(‘o:/temp’)
返回指定目录内容列表,不递归.
os也有open,read,write等方法,但是太底层,建议使用内建函数open,read,write,使用方法相识.

建立一个软链接
ln -s test t1

os.stat(path,,dir_fd=None,follow_symlinks=True)
本质上调用linux系统的stat.
Path:路径的string或者bytes,或者fd文件描述符
follow_symlinks True返回文件本身信息,False且如果是软连接则显示软连接本身,对于软连接本身,可以使用os.lstat方法
os.chmod(path,mode.
.dir_fd=None,follow_symlinks=True)
os.chomde(‘test’,0o777)
os.chmod(path,uid,gid)
改变文件的属主,属组,但需要足够的权限

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值