文件读写
-
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
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()
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)