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 一字符串形式写入和读取数据
管式输出
somefile.txt
输出:
‘wordcount’,6
f.seek(offset[,whence]) 把进行读写的位置移动到offset定义的位置
f.tell()返回当前文件的位置
f.readline() 读当前位置的一行
f.readlines() 读取一个文件所有的行并将其作为列表返回
r.writelines() 传入一个字符串列表,然后把所有的字符串写入文件或流
读取文件内容的选择
文件较小时:
当作一个字符串处理
当作字符串列表来处理
当文件比较大时,raed和writelines就比较占内存
可用while 和 wirteline代替
或者使用fileinput的input方法,能返回可用于for的可迭代对象,且每次只返回需要读取的部分
文件迭代器
文件对象也是可迭代的,酷!!
其它
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()
其它
相关文章推荐
- 【python学习笔记】4:精度控制/文件读/split()方法
- python学习(四)----文件相关方法
- Python学习_几种存取xls/xlsx文件的方法总结
- Python学习(16)File(文件)方法
- 深入学习python解析并读取PDF文件内容的方法
- Python学习(二) linux终端下运行.py文件的方法
- python 学习笔记(5) 文件I/O及方法
- Python学习之几种存取xls/xlsx文件的方法
- NetworkX学习笔记-3-Python中输出Gephi文件格式的方法
- Python学习文件(File)方法
- file()创建文件方法 分类: python python基础学习 2012-12-24 18:17 239人阅读 评论(0) 收藏
- 笨方法学习Python-习题20: 函数和文件
- Python--小甲鱼学习笔记--第28课:文件(文件打开方式、文件对象方法)
- 笨方法学习Python-习题17: 更多文件操作
- 深入学习Python解析并解密PDF文件内容的方法
- 笨方法学习Python-习题16: 读写文件
- Python 深度学习模型训练数据预处理 批文件重命名 os.listdir方法 os.rename方法 file.spilt方法
- python_基础学习_01_按行读取文件的最优方法
- Python学习笔记-XML大文件的XSD验证方法
- NetworkX学习笔记-3-Python中输出Gephi文件格式的方法