python 操作 linux系统目录/文件

文件读写

  • open函数

        f = open("123.txt", "r")
    

    文件打开模式

    • r
    • w
    • x
    • a
  • 避免文件句柄泄露

        try:
            f = open("123.txt")
            print(f.read())
        finally:
            f.close()
        
        # 使用 with
        with open("123.txt") as f:
            print(f.read())
    
  • 文件操作函数

    读函数

    • read
    • readline
    • readlines

    写函数

    • write
    • writelines
  • 文件对象可迭代

        with open('123.txt') as f:
            for line in f:
                print(line)
    

文件和文件路径管理

  • os.path 模块

        import os
        
        # 基本方法
        os.getcwd()
        
        os.listdir()
        
        # 拆分路径
        path = '/home/yxd/t/access.log'
        
        os.path.split(path) 
        
        os.path.dirname(path)
        
        os.path.basename(path)
        
        os.path.splittext(path)
        
        # 构建路径
        os.path.expanduser('~')
        
        os.path.expanduser('~mysql')
        
        os.path.expanduser('~yxd/t')
        
        os.path.abspath(".")
        
        os.path.abspath("..")
        
        os.path.join("~", "t", "a.py")
        
        os.path.isabs(".") # False
        
        os.path.abspath(__file__)
        
        os.path.pardir # ".."
        
        # 获取文件属性
        os.path.getatime()
        
        os.path.getctime()
        
        os.path.getmtime()
        
        os.path.size()
        
        # 判断文件类型
        os.path.exists()
        
        os.path.isfile()
        
        os.path.isdir()
        
        os.path.islink()
        
        os.path.ismount()
    
  • os模块管理文件和目录

        import os
        
        
        os.chdir() # 切换目录
        
        os.unlink()
        
        os.remove()
        
        os.rmdir()
        
        os.mkdir()
        
        os.rename()
        
        os.access()
        
        os.chmod()
    

查找文件

  • fnmatch

        import fnmatch
        
        
        fnmatch.fnmatch()
        
        fnmatch.fnmatchcase() # 忽略大小写
        
        fnmatch.filter()
        
        fnmatch.translate() # 正则
    
    • *匹配任何数量的字符
    • ?匹配单个字符
    • [seq]
    • [!seq]
  • glob

    比fnmatch更简单
        import glob
        
        
        glob.glob("*.txt")
        
        glob.glob("[a-c]?.txt")
    
  • os.walk

    遍历某个目录及其子目录
        import os
        
        for root, dirname, filename in os.walk(os.path.expanduser("~yxd/t")):
            dirname.remove("123.txt") # 不遍历指定文件夹
            print('filename')
    

高级文件处理接口 shutil

     import shutil
     
     ls
     
     shutil.copy('a.py', 'b.py') 
     
     shutil.copytree('dir1', 'dir2')
     
     shutil.move('a.py', 'b.py')
     
     shutil.move('a.py', 'dir1')
     
     shutil.rmdir('dir1')
     
     shutil.rmtree('dir1')

文件内容管理

  • 文件和目录比较 filecmp

        import filecmp
        
        filecmp.cmp('a.txt', 'b.txt')
        
        filecmp.cmpfiles('dir1','dir2', ['filename1', 'filename2'])
        
        filecmp.dircmp('dir1', 'dir2')
    
  • MD5 校验和比较

    MD5 哈希一般用于检查文件完整性,校验文件是否相同
    • shell
        md5sum /etc/passwd
    
    • python
        import hashlib
        
        d = hashlib.md5()
        
        with open('/ect/passwd') as f:
            for line in f:
                d.update(line)
        print(d.hexdigest())        
    

使用python管理压缩包

  • 使用 tarfile 读取和创建 tar 包

        import tarfile
        
        # 读取tar包
        with tarfie.open('123.tar') as t:
            for member_info in t.getmembers():
                print(member_info.name)
        t.getnames()
        t.extract()
        t.extractall()
        
        # 创建tar包
        with tarfile.open('123.tar', mode='w') as out:
            out.add('123.txt')
    
  • 使用tarfile 读取和创建压缩包

        tarfile.open('123.tar', mode='r:gz')
        
        tarfile.open('123.tar', mode='w:bz2')
    
  • 使用zipfile

        import zipfile
        
        # 读取zip文件
        myzip = zipfile.ZipFile('123.zip')
        
        myzip.namelist()
        
        myzip.extract()
        
        myzip.extractall()
        
        # 创建zip文件
        newzip = zipfile.ZipFile('new.zip', 'w')
        
        newzip.write('123.txt')
        
        newzip.close()
    
    zipfile 命令行
        python -m zipfile -c -l -e -t
    
  • shutil 创建读取压缩包

        import shutil
        
        shutil.get_achive_formats() # 获取支持的文件格式
        
        # 创建压缩包
        shutil.make_archive('backup', 'gztar') # 压缩当前目录文件
        shutil.make_archive('backup', 'gztar', '/home/')
        
        # 读取压缩包
        shutil.unpack_archive(filename, extract_dir, format)
    

执行外部命令

  • subprocess

        import subprocess
        
        # 快速方法
        subprocess.call()
        
        subprocess.check_call()
        
        subprocess.check_output()
        
        # popen类
        
        popen = subprocess.Popen('ls')
        
        popen.wait()
        
        popen.poll()
        
        popen.kill()
        
        popen.send_sognal()
        
        popen.terminate()
        
        popen.communicate()
    
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值