Python3-Cookbook-Study Notes chap5:文件与IO

1.读写文本数据

# 使用带有 rt 模式的 open() 函数读取文本文件
# Read the entire file as a single string
with open('somefile.txt', 'rt') as f:
    data = f.read()

# Iterate over the lines of the file
with open('somefile.txt', 'rt') as f:
    for line in f:
        # process line
        ...

# 为了写入一个文本文件,使用带有 wt 模式的 open() 函数
# Write chunks of text data
with open('somefile.txt', 'wt') as f:
    f.write(text1)
    f.write(text2)
    ...

# Redirected print statement
with open('somefile.txt', 'wt') as f:
    print(line1, file=f)
    print(line2, file=f)
    ...

# 在已存在文件中添加内容,使用模式为 at 的 open() 函数
with open('somefile.txt', 'rt', encoding='latin-1') as f:
    ...

2.打印输出至文件中

# 在 print() 函数中指定 file 关键字参数
with open('d:/work/test.txt', 'wt') as f:
    print('Hello World!', file=f)

3.使用其他分隔符或行终止符打印

# 在 print() 函数中使用 sep 和 end 关键字参数,以你想要的方式输出
print('ACME', 50, 91.5, sep=',')
print('ACME', 50, 91.5, sep=',', end='!!\n')

print(','.join(('ACME','50','91.5')))

4.读写字节数据

# 使用模式为 rb 或 wb 的 open() 函数来读取或写入二进制数据
# Read the entire file as a single byte string
with open('somefile.bin', 'rb') as f:
    data = f.read()

# Write binary data to a file
with open('somefile.bin', 'wb') as f:
    f.write(b'Hello World')

5.文件不存在才能写入

# 在 open() 函数中使用 x 模式来代替 w 模式的方法来解决这个问题

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

# 测试文件是否存在
import os
if not os.path.exists('somefile')

6.字符串的I/O操作

# 使用 io.StringIO() 和 io.BytesIO() 类来创建类文件对象操作字符串数据
# io.StringIO 只能用于文本。如果你要操作二进制数据,要使用 io.BytesIO 类来代替
s = io.StringIO('Hello\nWorld\n')

7.读写压缩文件

# gzip compression
import gzip
with gzip.open('somefile.gz', 'rt') as f:
    text = f.read()

# bz2 compression
import bz2
with bz2.open('somefile.bz2', 'rt') as f:
    text = f.read()

8.固定大小记录的文件迭代

from functools import partial

RECORD_SIZE = 32

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

9.读取二进制数据到可变缓冲区中 —— 使用文件对象的 readinto() 方法

10.内存映射的二进制文件

import os
import mmap

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)

11.文件路径名的操作

import os
path = '/Users/beazley/Data/data.csv'

# Get the last component of the path
os.path.basename(path)

# Get the directory name
os.path.dirname(path)

# Join path components together
os.path.join('tmp', 'data', os.path.basename(path))

# Expand the user's home directory
path = '~/Data/data.csv'
os.path.expanduser(path)

# Split the file extension
os.path.splitext(path)

12.测试文件是否存在

import os
os.path.exists('/etc/passwd')

# Is a regular file
os.path.isfile('/etc/passwd')

# Is a directory
os.path.isdir('/etc/passwd')

# Is a symbolic link
os.path.islink('/usr/local/bin/python3')

os.path.getsize('/etc/passwd')
os.path.getmtime('/etc/passwd')
import time
time.ctime(os.path.getmtime('/etc/passwd'))

13.获取文件夹中的文件列表 —— os.listdir() 函数

import os
names = os.listdir('somedir')


# Get all regular files
names = [name for name in os.listdir('somedir')
        if os.path.isfile(os.path.join('somedir', name))]

# Get all dirs
dirnames = [name for name in os.listdir('somedir')
        if os.path.isdir(os.path.join('somedir', name))]

pyfiles = [name for name in os.listdir('somedir')
            if name.endswith('.py')]

import glob
pyfiles = glob.glob('somedir/*.py')

from fnmatch import fnmatch
pyfiles = [name for name in os.listdir('somedir')
            if fnmatch(name, '*.py')]

15.忽略文件名编码

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值