1. 读取文件
方法: all_the_text = open('thefile.txt').read()
但是为了安全起见还是给打开的文件对象指定一个名字,这样在完成之后可以迅速关掉,防止无用文件对象占用内存;
例子: file_object = open('thefile.txt',r) try: all_the_text = file_object.read() #read()将文件中所以字符都读到all_the_text中去变成了一个巨大的字符串, finally: file_object.close()
不一定要加try,finally语句,但是加了更好,可以保证文件对象被关闭即使在读取中发生了严重错误;
如果要读入100个字符也可以直接:
text=file.read(100),
如要一行行处理还可以:
ff = file_object.readlines()
#读出来是 list 类型,而且每行末尾都有'\n'符号;既然是一行行的,那么打印也要一行行的显示:
for line in ff:
print line #此时line类型是string,而ff依然是list类型
#这样打印出来不会乱,而如果直接 print ff 则会一次性打印整个ff序列,而汉子在序列里面是ASCII,会导致汉子打印不出来,而且特别乱;所以要一行行的打印’
而最简单方法:
for line in file_object: line = line.rstrip('\n') print line 此时line是string类型,但每行末尾都有'\n'符号;可以再for主体部分加一句:line = line.rstrip('\n') 在每行末尾去掉'\n'符号,而line.restrip()则默认去掉空白符;
2. 写入文件
最方便的一个方法:
open('thefile.txt','w').write(all_the_text)
但是最好还是给文件对象指定一个名字,这样方便关闭文件对象
file_object = open('thefile.txt','w') file_object.write(all_the_text) file_object.close()
实际上用‘w’或者'wb'打开的文件,都是空文件;哪怕是这个文件不是空文件,用这两种方式打开后,也会被清空;这种情况,就要用到‘a’或者‘ab’来打开则不会清空;
如果用'a+'这种方式来打开的话不能写的时候文件不会被清空,而且还可以读取文件呢;
注意:无论读还是写,文件打开之后游标会一直往后走,直到关闭;当然也可以使用seek()函数来控制游标
3. 搜索和替换文件中的文本
replace(search_text,replace_text),用于字符串的替换;
4. 从文件中读取指定的行
enumerate():遍历序列中的元素以及下标
>>> for i,j in enumerate(['a','b','c']): ... print i,j ... 0 a 1 b 2 c
函数模块:
def getline(thefilepath,desired_line_number): if desired_line_number < 1: return ' ' for current_line_number,line in enumerate(open(thefilepath,'ru')): if current_line_number == desired_line_number-1: return line return ''
库文件 linecache
当对文件进行多次读取时,linecache,特别有用,它读取并缓存指定文件里的所有文本;用clearcache()来释放被用作缓存的内存,checkcache()来确保缓存中的存储是最新的;
import linecache theline = linecache.getline(thefilepath,desired_line_number) #简单一句就可以得到文件指定行的文本了,方便吧;
5. 处理文件中的每一个单词
首先看一个函数split()
Python split()通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串
实例:
#!/usr/bin/python str = "Line1-abcdef \nLine2-abc \nLine4-abcd";print str.split( );print str.split(' ', 1 ); 以上实例输出结果如下: ['Line1-abcdef', 'Line2-abc', 'Line4-abcd']['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
对每一个词做一些处理,最好的就是两重循环,一个用于处理行,一个用于处理单词
for line in open(thefilepath): for word in line.split(): dosometingwith(word)
6. 处理zip数据
6.1 从zip文件中读取数据
任务检查一个zip文档中所有子项,并打印子项名称,以及大小;
#!/usr/bin/env python #encoding:utf-8 import zipfile #以’r‘打开zip文件, z = zipfile.ZipFile("text.txt.zip","r") #从zip文件列表中读取子项名并读取出来计算其字节数 for filename in z.namelist(): print 'File:',filename byte = z.read(filename) print 'has',len(byte),'byte'