Python Cookbook学习记录 ch2_6/7/8_2013/10/27

2.6 处理文件中的每一词

a.先获取每一行,再通过split()方法获取每一个词,之后再进行处理

for line in open(thefilepath):
    for word in line.split():
        dosomethingwith(word)

b.使用生成器(generator),将元素的迭代,和元素的处理分开

def words_of_file(thefilepath, line_to_words=str.split):
    the_file = open(thefilepath):
    for line in the_file:
        for word in line_to_words(line):
            yield word
    the_file.close()
for word in words_of_file(thefilepath):
    dosomethingwith(word)

2.7 随机输入输出

适用于固定长度记录的大二进制文件

使用file.seek()方法获取文件头部的偏移字节,再通过read()方法获得文件内容

thefile = open('somebinfile', 'rb')
record_size = 48
record_number = 6
thefile.seek(record_size * record_number)
buffer = thefile.read(record_size)

2.8更新随机存储文件

包含固定长度记录的大二进制文件,读取某一条记录,并修改某些字段的值,然后写回文件

import struct
format_string = '8l'                # e.g., say a record is 8 4-byte integers
thefile = open('somebinfile', 'r+b')
record_size = struct.calcsize(format_string)
thefile.seek(record_size * record_number)
buffer = thefile.read(record_size)
fields = list(struct.unpack(format_string, buffer))
# Perform computations, suitably modifying fields, then:
buffer = struct.pack(format_string, *fields)
thefile.seek(record_size * record_number)
thefile.write(buffer)
thefile.close()

 

posted on 2013-10-27 21:22  七海之风  阅读(129)  评论(0)    收藏  举报

导航