python学习之文件方法
open(file[, mode[,buffering]] )
mode:'r','w','a','b','+'
buffer:
False:直接对硬盘读写,比较慢
True:用内存代替硬盘,只有使用flush和close后才更新硬盘数据
类文件对象的方法
open函数打开文件,生成文件对象
f.write f.read 一字符串形式写入和读取数据
1 f = open('/tmp/temp.txt', 'rw') 2 f.read(4) 3 f.write('hello') 4 f.close()
管式输出
somefile.txt
hello world nice to see you
1 #somescript.py 2 import sys 3 text = sys.stdin.read() 4 words = text.split() 5 wordscount = len(words) 6 print 'wordscount', wordscount
1 $ cat somefile.txt | python somescript.py
输出:
‘wordcount’,6
f.seek(offset[,whence]) 把进行读写的位置移动到offset定义的位置
1 f = open(r'/tmp/temp.txt', 'w') 2 f.write('01234567890123456789') 3 f.seek(5) 4 f.write('hello,world') 5 f.close() 6 f.open(r'/tmp/temp.txt', 'r') 7 f.read() ## '01234hello,world6789'
f.tell()返回当前文件的位置
1 f.open(r'/tmp/temp.txt', 'r') 2 f.read() ## '01234hello,world6789' 3 f.read(3) ##'012' 4 f.read(2) ##'34' 5 f.tell() ##5L
f.readline() 读当前位置的一行
f.readlines() 读取一个文件所有的行并将其作为列表返回
r.writelines() 传入一个字符串列表,然后把所有的字符串写入文件或流
读取文件内容的选择
文件较小时:
当作一个字符串处理
1 f = open(filename, 'r') 2 for char in f.read(): 3 print char 4 f.close()
当作字符串列表来处理
1 f = open(filename, 'r') 2 for line in f.readlines(): 3 print line 4 f.close()
当文件比较大时,raed和writelines就比较占内存
可用while 和 wirteline代替
1 f = open(filename, 'r') 2 while True: 3 line = f.writeline() 4 if not line: 5 break 6 print line 7 f.close()
或者使用fileinput的input方法,能返回可用于for的可迭代对象,且每次只返回需要读取的部分
1 import fileinput 2 for line in fileinput,input(filename): 3 print line
文件迭代器
文件对象也是可迭代的,酷!!
1 f = open(filename) 2 for line in f: 3 print line 4 f.close()
其它
浙公网安备 33010602011771号