Python–cookbook–5.文件与IO

Python–cookbook–5.文件与IO

文章目录

  • Python–cookbook–5.文件与IO
      • 导入对应模块
      • 读写文本数据
      • 打印输出到文件中
      • 使用分割符或行终止符打印
      • 读写字节数据 rb wb
      • 文件不存在才能写入 x模式替代w模式
      • 读写压缩文件
      • 固定大小记录的文件迭代
      • 读取二进制数据到可变缓冲区中
      • 内存映射的二进制文件
      • 文件路径名的操作
      • 测试文件是否存在
      • 文件名的匹配
      • 忽略文件名编码
      • 打印不合法的文件名

导入对应模块

import array
import io
import functools
import os
import mmap
import time
import glob
import fnmatch
import sys
import pickle

读写文本数据

# rt模式下,python在读取文本时会自动把\r\n转换成\n
# read:读所有  readline:读一行  readlines:读所有列表保存
# with open('test.txt', 'rt') as f:
    # data = f.read()
    # print(data)
    # for line in f:
    #     print(line, end='')
# write(str 或 bytes):写入字符串或字节串。只有以二进制模式(b 模式)打开的文件才能写入字节串。
# writelines(可迭代对象):写入多个字符串或多个字节串
# with open('somefile.txt', 'wt') as f:
#     f.write('123\n')
#     f.write('456\n')
#     f.writelines(['789\n', '000\n'])
# 常见的编码是 ascii, latin-1, utf-8 和 utf-16
# 不使用with,需要手动关闭文件

打印输出到文件中

# with open('somefile.txt', 'wt') as f:
#     print('Hello World! Yeah! HaHa', file=f)

使用分割符或行终止符打印

row = ('ACME', 50, 91.5)
print(*row, sep=';')

读写字节数据 rb wb

# with open('somefile.bin', 'wb') as f:
#     f.write(b'Hello World')
# 从二进制模式的文件中读取或写入文本数据,必须确保要进行解码和编码操作
# with open('somefile.bin', 'rb') as f:
#     data = f.read(16)
#     text = data.decode('utf-8')
#     print(text)
# with open('somefile.bin', 'wb') as f:
#     text = 'Hello World!!!'
#     f.write(text.encode('utf-8'))

文件不存在才能写入 x模式替代w模式

# with open('somefile', 'xt') as f:
#     f.write('Hello\n')

# 字符串的I/O操作
# 操作类文件对象的程序来操作文本或二进制字符串
# 使用 io.StringIO() 和 io.BytesIO() 类来创建类文件对象操作字符串数据
s = io.StringIO()
s.write('Hello World\n')
print('This is a test', file=s)
u = s.getvalue()  # 'Hello World\nThis is a test\n'

读写压缩文件

# gzip bz2

固定大小记录的文件迭代

# RECORD_SIZE = 32
# with open('somefile.data', 'rb') as f:
#     records = iter(functools.partial(f.read, RECORD_SIZE), b'')
#     for r in records:

读取二进制数据到可变缓冲区中

def read_into_buffer(filename):
    buf = bytearray(os.path.getsize(filename))
    with open(filename, 'rb') as f:
        f.readinto(buf)
    return buf

内存映射的二进制文件

def memory_map(filename, access=mmap.ACCESS_WRITE):
    size = os.path.getsize(filename)
    fd = os.open(filename, os.O_RDWR)
    return mmap.mmap(fd, size, access=access)

文件路径名的操作

path = r'E:\###技术栈学习###\python cook book\5.文件与IO.py'
print(os.path.basename(path))
print(os.path.dirname(path))
print(os.path.join('tmp', 'data', os.path.basename(path)))
print(os.path.splitext(path))

测试文件是否存在

print(os.path.exists('5.文件与IO.py'))
print(os.path.exists('/tmp/spam'))
# 测试文件类型
print(os.path.isfile('5.文件与IO.py'))  # 文件
print(os.path.isdir(r'E:\###技术栈学习###\python cook book'))  # 目录
# 绝对路径
print(os.path.realpath('5.文件与IO.py'))
# 获取文件大小和修改日期
print(os.path.getsize('5.文件与IO.py'))
print(time.ctime(os.path.getmtime('5.文件与IO.py')))
# 获取文件夹中的文件列表
print(os.listdir(r'E:\###技术栈学习###\python cook book'))

文件名的匹配

# glob fnmatch模块
pyfiles = glob.glob('*.py')
print(pyfiles)
pyfiles2 = [name for name in os.listdir(r'E:\###技术栈学习###\python cook book')
            if fnmatch.fnmatch(name, '*.py')]
print(pyfiles2)

忽略文件名编码

print(sys.getfilesystemencoding())

打印不合法的文件名

# for name in files:
#     try:
#         print(name)
#     except UnicodeEncodeError:
#         print(bad_filename(name))

你可能感兴趣的:(python--相关特性,python,开发语言)