0%

Python小技巧(5)--文件和IO

文件和IO----来源于cookbook第五章

记录第五章中比较有意思的部分


open函数打开文件的小技巧

由于有些文件中会出现编码错误或与当前主机不匹配,使用open函数时可以增加errors='ignore'来忽略掉错误的编码。

1
2
3

g = open("somefile.txt", 'rt', encoding = 'utf-8', errors = 'ignore')

使用print函数重定向到文件

使用print函数的file = handler参数即可

1
2
3
4
5
6

l = [1,2,'3',(4,5)]

with open("file","w") as f:
print(*l, sep = ',', file = f)

对不存在的文件进行写入操作

直接使用xt模式来操作文件即可

1
2
3
4
5
6
7

with open("somefile", 'wt') as f: # 当somefile不存在时会报错
...

with open("somefile", 'xt') as f: # 当somefile不存在时会创建,存在时不影响
...

将二进制文件做内存映射

使用mmap模块来创建映射,这样可以直接访问,而不需要频繁的seek、read等操作。

另外,由于虚拟内存的存在,多个python解释器可以映射到同一个文件上从而实现共享数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

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)

m = memory_map("data")

# 此时就可以像操作数组那样操作m

print(len(m))
print(m[:34])
m[:11] = b'hello world'
m.close()

将字节数据写入文本文件

只需要简答的将字节数据写入到文件底层buffer中就可以了。

在python中调用print时,事实上调用了sys.stdout.write(obj+'\n')

而stdout就像是一个类文件对象,因为你可以将他赋值给任意的一个文件对象,重定向输出

原始的sys.stdout指向控制台,如果把文件的对象引用赋给sys.stdout,那么print调用的就是文件对象的write方法

而buffer是缓冲区,所以此操作就是不调用上层的write方法而直接写入底层的缓冲区

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 示例一

import sys

sys.stdout.buffer.write(b'hello\n')


# 示例二

import sys

sys.stdout = open("filename","xt")

sys.stdout.buffer.write(b'hello\n')

创建临时文件与文件夹

tempfile模块中有各种实现了上下文管理协议的函数来处理临时文件

1
2
3
4
5
6

from tempfile import TemporaryFile

with TemporaryFile('w+t', encoding = 'utf-8', errors = 'ignore', delete = True):
...

序列化python对象

pickle模块的dump和load函数就足以处理这些

注意不要对来源不明的对象进行load,因为这会产生副作用,严重甚至可能导致计算机被入侵。

1
2
3
4
5
6
7
8
9
10

import pickle

a = [1,2,3]

with open("filename",'wb') as f:
pickle.dump(a,f)
...
pickle.load(a,f)