您的位置:首页 > 编程语言 > Python开发

python学习之文件方法

2012-06-01 11:33 579 查看
open(file[, mode[,buffering]] )

mode:'r','w','a','b','+'

buffer:

False:直接对硬盘读写,比较慢

True:用内存代替硬盘,只有使用flush和close后才更新硬盘数据

类文件对象的方法

open函数打开文件,生成文件对象

f.write f.read 一字符串形式写入和读取数据

f = open('/tmp/temp.txt', 'rw')
f.read(4)
f.write('hello')
f.close()


管式输出

somefile.txt

hello world nice to see you


#somescript.py
import sys
text = sys.stdin.read()
words = text.split()
wordscount = len(words)
print 'wordscount', wordscount


$ cat somefile.txt | python somescript.py


输出:

‘wordcount’,6

f.seek(offset[,whence]) 把进行读写的位置移动到offset定义的位置

f = open(r'/tmp/temp.txt', 'w')
f.write('01234567890123456789')
f.seek(5)
f.write('hello,world')
f.close()
f.open(r'/tmp/temp.txt', 'r')
f.read()  ## '01234hello,world6789'


f.tell()返回当前文件的位置

f.open(r'/tmp/temp.txt', 'r')
f.read()  ## '01234hello,world6789'
f.read(3)  ##'012'
f.read(2)  ##'34'
f.tell()  ##5L


f.readline() 读当前位置的一行

f.readlines() 读取一个文件所有的行并将其作为列表返回

r.writelines() 传入一个字符串列表,然后把所有的字符串写入文件或流

读取文件内容的选择

文件较小时:

当作一个字符串处理

f = open(filename, 'r')
for char in f.read():
print char
f.close()


当作字符串列表来处理

f = open(filename, 'r')
for line in f.readlines():
print line
f.close()


当文件比较大时,raed和writelines就比较占内存

可用while 和 wirteline代替

f = open(filename, 'r')
while True:
line = f.writeline()
if not line:
break
print line
f.close()


或者使用fileinput的input方法,能返回可用于for的可迭代对象,且每次只返回需要读取的部分

import fileinput
for line in fileinput,input(filename):
print line


文件迭代器

文件对象也是可迭代的,酷!!

f = open(filename)
for line in f:
print line
f.close()


其它
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: