打开文件
open(name[mode[,buffing])
name: 是强制选项,模式和缓冲是可选的
#如果文件不在,会报下面错误:
>>> f = open(r'D:\text.txt','r') Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: [Errno 2] No such file or directory: 'D:\\text.txt'文件模式
NOTE:
1. 默认的方式,比如说open(‘filename‘)是读模式
2. r+, 则表示可读写
3. 如果是二进制文件或图形文件,则必须用缓冲模式
4. 普通的w模式会覆盖文件的内容,a模式则不会.
5. rb则可以用来读取二进制文件.
6, 通过参数模式中使用U参数,能够在打开文件时使用通用的换行符支持模式,无论\r,\n\r,都会换成\n,而不用考虑运行的平台.
缓冲:
第三个参数,可选
0或者False: 无缓冲,所有操作直接针对硬盘
1或者True: 有缓冲,内存代替硬盘,速度快,只有close,flush才写入硬盘同步.
> 1 : 表示缓冲区的大小
-1 : 表示默认的缓冲区大小
基本文件方法
NOTE: 类文件对象是支持一些文件的方法的对象,比如file方法,最重要的两个方法,read,write方法.还有urllib.urlopen返回对象,他们支持的方法有: read,readline,readlines
三种标准的流
sys.stdin :标准输入流,可通过输入或者使用管道把它和其它程序的标准输出链接起来提供文本
sys.stdout :放置input,raw_input写入的数据,可在屏幕上显示,也可通过|连接到其它程序的标准输入
sys.stderr :错误信息,比如说栈追踪被写入sys.stderr.
读和写
最重要的能力是提供读写
#对空文件来说: 提供写时,会在已在字符串末尾追加,
>>> f = open('somefile.txt','w')
>>> f.write('Hello,')
>>> f.write('World!')
>>> f.close()
#somefile.txt文件内容
Hello,World!#对于非空文件:提供w方法时,会覆盖文件中的内容
>>> f = open('somefile','w')
>>> f.write('This is 1st line.\n')
>>> f.write('This is 2nd line.')
>>> f.close()
#somefile.txt文件内容
This is 1st line.
This is 2nd line.简单读取的例子:
>>> f = open('somefile.txt','r')
>>> f.read(16)#先读取16个字符
'This is 1st line'
>>> f.read() #会读取剩下的内容,除非seek定位到0,重新读取
'.\nThis is 2nd line.'
>>> f.close()管道输出
$ cat somefile.txt | python somescript.py | sort
一个简单例子: 统计一个文本中单词的数量
$ cat somefile.txt
This is a book!
That is a dog!
Who are you?
脚本清单
#somescript.py import sys text = sys.stdin.read() words = text.split() print "Word Count:", len(words)输出结果:
# cat somefile.txt | python somescript.py Word Count: 11随机访问:
用seek和tell来访问自己感兴趣的部分
seek(offset[,whence]). offset,偏移量,Whence值
0: 开始位置
1: 当前位置
2: 文件末尾
简单例子:
>>> f = open('somefile.txt','w')
>>> f.write('01234567890123456789')
>>> f.seek(5)
>>> f.write('Hello,World!')
>>> f.close()
>>> f = open('somefile.txt')
>>> f.read()
'01234Hello,World!789'
#用tell来返回当前文件的位置
>>> f = open('somefile.txt')
>>> f.read(3)
'012'
>>> f.read(2)
'34'
>>> f.tell()
5L读写行:
readline : 读取行,包括换行符
readlines: 读取所有行
write: 写一行, 注意:没有writeline方法
writelines: 写多行
NOTE: 如何判断不同的行以什么结尾? os.linesep
#UNIX >>> import os >>> os.linesep '\n' #WINDOWS >>> import os >>> os.linesep '\r\n'关闭文件
时刻记得close()来关闭文件,这样做的目的:
1. 出于安全考虑,防止文件因为某些原因崩溃,写不进数据
2. 出于数据同步考虑,close(),才会往硬盘中写数据
3. 出于效率的考虑,内存中的数据可清空一部分出来
为了确保程序结束时close(),可以用try/finally结合使用
# Open your file here
try:
# Write data to your file
finally:
file.close()NOTE: 一般文件在close()之后才会写入硬盘,如果想不执行close()方法,又可以看到写入的内容,那么flush就派上用场了.
使用基本方法:
#测试文本somefile.txt
Welcome to this file
There is nothing here except
This stupid haiku
首先读取指定字符
>>> f = open(r'd:\Learn\Python\somefile.txt') >>> f.read(7) 'Welcome' >>> f.read(4) ' to ' >>> f.close()其次读取所有的行
>>> f = open(r'd:\Learn\Python\somefile.txt','r') >>> print f.read() Welcome to this file There is nothing here except This stupid haiku接着是读取行
>>> f.close() >>> f = open(r'd:\Learn\Python\somefile.txt') >>> for i in range(3): ... print str(i) + ':' + f.readline() ... 0:Welcome to this file 1:There is nothing here except 2:This stupid haiku再读取所有行:
>>> import pprint
>>> pprint.pprint(open('somefile.txt').readlines())
['Welcome to this file\n',
'There is nothing here except\n',
'This stupid haiku']下面是写文件
>>> f = open(r'somefile.txt','w')
>>> f.write('this\nis no\nhaiku')
>>> f.close()
运行文件后,内容如下:
this
is no
haiku最后是writelines
>>> f = open(r'somefile.txt')
>>> lines = f.readlines()
>>> f.close()
>>> lines[1] = "isn't a\n"
>>> f = open('somefile.txt','w')
>>> f.writelines(lines)
>>> f.close()
运行后,文件内容如下:
this
isn't a
haiku对文件内容进行迭代
基本的方法如: read,readline,readlines,还有xreadline和文件迭代器
下面的例子都使用的虚拟函数process(),表示每个字符或每行处理过程
def process(string):
print ‘Processing‘, string
更有用的实现是:在数据结构中存储数据,计算和值。用re模块来替代模式或者增加行号.如果要实现上面的功能,
则应该讲filename变量设置为实际的文件名.
按字节处理
def process(string):
print 'Processing...', string
f = open('somefile.txt')
char = f.read(1)
while char:
process(char)
char = f.read(1)
f.close()代码重用通常是件坏事,懒惰是美德。重写下代码如下:
def process(string):
print 'Processing...', string
f = open('somefile.txt')
while True:
char = f.read(1)
if not char:
break
process(char)
f.close()NOTE: 这样写就比上面要好,避免了重复的代码.
按行操作
f = open(filename)
while True:
line = f.readline()
if not line:
break
process(line)
f.close()读取所有内容
如果文件不是很大,可以用read(),或者readlines()读取的内容作为字符串来处理.
#用read来迭代每个字符串
f = open(r'D:\Work\Python\somefile.txt')
for char in f.read():
process(char)
f.close()#用readlines来迭代行
f = open(r'D:\Work\Python\somefile.txt','r')
for line in f.readlines():
process(line)
f.close()使用fileinput实现懒惰行迭代
在需要对一个大文件进行迭代时,readlines会占用太多的内存。这个时候可以使用while循环和readline方法来替代。
import fileinput
def process(string):
print 'Processing...', string
for line in fileinput.input('somefile.txt'):
process(line)文件迭代器
#Python中文件是可以迭代的,写起来也很优雅
f = open('somefile.txt')
for line in f:
print line,
f.close()#如果希望Python来完成关闭的动作,对文件进行迭代,而不使用变量存储变量
#代码可以更加精简
for line in open('somefile.txt'):
print line,sys.stdin也是可以迭代的,简单代码如下:
import sys
for line in sys.stdin:
print line,
运行结果:
D:\Work\Python>python file.py
#输入下面两行
Hello,World!
Hello,Jerry!
^Z
#按下CTRL+Z键后,输入的内容,显示
Hello,World!
Hello,Jerry!#可以对文件迭代器执行和普通迭代器相同的操作。比如将它们转换为字符串列表,这样所达到的效果和使用readlines一样.如下例:
>>> f = open('somefile.txt','w')
>>> f.write('First line\n')
>>> f.write('Second line\n')
>>> f.write('Third line\n')
>>> f.close()
>>> lines = list(open('somefile.txt'))
>>> lines
['First line\n', 'Second line\n', 'Third line\n']
>>> first,second,third = open('somefile.txt')
>>> first
'First line\n'
>>> second
'Second line\n'
>>> third
'Third line\n'NOTE:
1.用序列来做解包操作非常使用
2.读文件操作时,可以不用close()
------
本章新函数
file(name[,mode[,buffering]]) 打开一个文件并返回一个文件对象
open(name[,mode[,buffering]]) file的别名;在打开文件,使用open而不是file
<<Python基础教程>>学习笔记 | 第11章 | 文件和素材
原文:http://blog.csdn.net/jerry_1126/article/details/39643149