标签:
例子: file_object = open(‘thefile.txt‘,r) try: all_the_text = file_object.read() #read()将文件中所以字符都读到all_the_text中去变成了一个巨大的字符串, finally: file_object.close()
不一定要加try,finally语句,但是加了更好,可以保证文件对象被关闭即使在读取中发生了严重错误;
text=file.read(100),
ff = file_object.readlines()
for line in file_object: line = line.rstrip(‘\n‘) print line 此时line是string类型,但每行末尾都有‘\n‘符号;可以再for主体部分加一句:line = line.rstrip(‘\n‘) 在每行末尾去掉‘\n‘符号,而line.restrip()则默认去掉空白符;
open(‘thefile.txt‘,‘w‘).write(all_the_text)
file_object = open(‘thefile.txt‘,‘w‘) file_object.write(all_the_text) file_object.close()
>>> 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 ‘‘
import linecache theline = linecache.getline(thefilepath,desired_line_number) #简单一句就可以得到文件指定行的文本了,方便吧;
#!/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)
#!/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‘
标签:
原文地址:http://www.cnblogs.com/Aiapple/p/5388679.html