Python 文本处理

大多数的程序在实际运行中,需要保存数据或者从文件中将相关数据读取出来,比如游戏存档操作,这就需要使用文件的一些接口对文件进行操作,常见的文件操作有open、read、write、close等。
我们在工程目录下新建一个txt文件test.txt
然后我们创建一个Python程序,打开该文件,并读取内容显示

# -*-coding:utf-8 -*-
__author__ = 'daydayman'
f = file('test.txt')
data = f.read()
print data
f.close()

程序的运行结果:

C:\Python27\python.exe F:/python/python_proj/file.py
hello world!
hello python!
life is short,you do need Python!
Process finished with exit code 0

我们在读取文件时,可以使用readline/readlines函数行读取和操作:

# -*-coding:utf-8 -*-
f = file('test.txt', 'r')

for data in f.readlines():
    print data
f.close()

Readline与readlines函数的区别是,readlines自动将文件内容分成一个行的列表,该列表可以由Python的for循环进行处理,而readline每次只读取一行,通过速度会比readlines慢得多。一般情况下,当文件过大或者没有足够的内存可以一次读取整个文件时,才会使用readline。
Readline的使用:

# -*-coding:utf-8 -*-
f = file('test.txt', 'r')
while True:
    data = f.readline()
    if(len(data) == 0):
        break
    print data
f.close()

两者运行结果都是一样的:

C:\Python27\python.exe F:/python/python_proj/file.py
hello world!
hello python!
life is short,you do need Python!

Process finished with exit code 0

写操作

# -*-coding:utf-8 -*-
str = 'add a new text line'
f = file('write_test.txt', 'w')
f.write(str)
f.close()
f = file('write_test.txt', 'r')
data = f.read()
print data
f.close()

运行结果:

C:\Python27\python.exe F:/python/python_proj/file.py
add a new text line

Process finished with exit code 0

pickle/cpickle标准库

除了基本的文件操作接口外,Python标准库还提供了pickle/cpickle模块,实现了存储的输入输出功能。Pickle实现了一种算法,通过序列化操作,可以将任意一个Python对象转化成一系列字节,代表对象的字节流恶意被传输或存储,再重构后创建一个拥有相同特征新的对象。Cpickle使用C编码实现的,所以在运行效率上要比pickle高,但是cpickle模块中定义的类型不能被继承,如果在实际开发中,没有使用类,推荐使用cpickle。

# -*-coding:utf-8 -*-
import cPickle
data1 = ['hello world', 1024,45]
data2 = (12,23,34)
data3 = {'name':'lilei','age':23}
f = open("test.txt", 'w')
cPickle.dump(data1, f)
cPickle.dump(data2, f)
cPickle.dump(data3, f)
f.close()

f = open('test.txt', 'rb')
load1 = cPickle.load(f)
load2 = cPickle.load(f)
load3 = cPickle.load(f)
print load1
print load2
print load3

运行结果:

C:\Python27\python.exe F:/python/python_proj/file.py
['hello world', 1024L, 45L]
(12L, 23L, 34L)
{'age': 23L, 'name': 'lilei'}

Process finished with exit code 0

Dump()和load()函数是pickle模块中的两个主要函数。Dump函数接受一个数据对象和一个文件句柄作为一个参数,把数据对象以特定的格式保存到文件句柄指定的文件中。当我们使用load函数从文件中取出dump保存的对象时,通过反序列化操作,会恢复原来对象的格式。

《Linux三剑客》视频教程,从零开始快速掌握Linux开发常用的工具:Git、Makefile、vim、autotools、debug,免费赠送C语言视频教程,C语言项目实战:学生成绩管理系统。详情请点击淘宝链接:Linux三剑客