文件和流
1. 打开文件
- 使用open函数打开文件
# open用法
#open(name[, mode[, buffering]])
#第一个参数文件名,返回一个文件对象
>>> open(r'd:\123.txt')
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
open(r'd:\123.txt')
IOError: [Errno 2] No such file or directory: 'd:\\123.txt'
#打开的文件不存在时引发一个IOError异常
- 文件模式
open的第二个参数是,文件打开模式,默认为‘r’
值 | 描述 |
---|---|
‘r’ | 读模式 |
‘w’ | 写模式 |
‘a’ | 追加模式 |
‘b’ | 二进制模式(可以添加到其他的模式中) |
‘+’ | 读/写模式(可添加到其他模式中使用) |
二进制模式,二进制模式和文本模式区别不大,主要是在不同平台文本模式会对换行符进行自动转换,二进制模式则不会,python中换行是‘\n’,文本模式下读写文件是会自动把平台对应的换行(如windows上‘\r\n’,mac上‘\r’)转换为python的换行
- 缓冲
open函数的第三个参数为缓冲,为0时无缓冲,为1时使用缓冲,当使用缓存时,对文件的修改在flush或close时才写入到硬盘,大于1的数字代表缓冲区大小(单位字节),-1(或任意负数)代表使用默认的缓冲大小
2. 基本文件方法
-
文件/流,支持一些file类的对象称为类文件对象或者流,最重要的是支持read或write方法,或者两者兼之,sys模块的3种流即文件或者类文件对象
-
文件读/写
# 文件写,每次调用f.write(string)时,会向文件中追加string的值 >>> f = open(r'd:\sometext.txt', 'w') >>> f.write('Hello, ') >>> f.write('World!') >>> f.close() # 文件读,调用read读取文件,参数表示需要读取多少个字符,不提供读取文件剩余的所有部分 >>> f = open(r'd:\sometext.txt', 'r') >>> f.read(4) 'Hell' >>> f.read() 'o, World!'
-
管道输出,管道输入的内容可以通过stdin的read方法读入
#! /bin/sh # -*- coding: utf-8 -*- # file name: somestript.py import sys text = sys.stdin.read() words = text.split() wordcount = len(words) print 'Wordcount:', wordcount #somefile.txt #Your mothor was a hamster and your #father smelled of elderberries #运行cat somefile.txt | python somesctript.py #输出 #Wordcount: 11
-
任意位置读取seek和tell
# seek(offset[, whence]),这个方法把当前位置(进行读写的位置)移动到由offset和whence定义的位置,Offset类是一个字节(字符)数,表示偏移,whence默认0,表示从文件开头开始计算,1表示相对当前位置,此时offset可以为负,2表示相对于文件结尾 # tell放回当前文件的位置 >>> f = open(r'd:\sometext.txt', 'w') >>> f.write('01234567890123456789') >>> f.seek(5) >>> f.write('Hello, World!') >>> f.close() >>> f = open(r'd:\sometext.txt') >>> f.read(3) '012' >>> f.read() '34Hello, World!89' >>> f.tell() 20L
-
读写行
# 1. readline,读取单独的一行,使用非负整数指明可以读取的最大字符数 # 2. readlines,读取文件中的所有行,以列表返回 # 3. writeliens,传入一个字符串的列表,把所有内容写入到文件,不会新增行,需要自己添加 #没有writeline方法,可以使用write
-
关闭文件
应该牢记使用close方法关闭文件,特别是写入过的文件,因为python可能会有缓存,如果程序崩溃了,那么写入的数据根本不会写入文件,安全起见,要在使用完文件后关闭
# 1. 确保文件关闭第一种方法,使用try/finally语句,并且在finally子句中调用文件关闭方法 #open your file here try: #write to file finally: file.close() # 2. 使用专为这种情况设计的语句with with open(r"somefile.txt") as f: do_something(f) #with语句打开的文件并赋值到f,文件语句在结束后会自动关闭文件,即使由于异常结束也是如此
-
文件基本方法使用
# 一个简单的文件文件sometext.txt #Welcome to this file #There is nothing here execpt #This stupid kaiku # 1. read(n) >>> f = open(r'd:\sometext.txt') >>> f.read(7) 'Welcome' >>> f.read(4) ' to ' >>> f.close() # 2. read >>> f = open(r'd:\sometext.txt') >>> print f.read() Welcome to this file There is nothing here execpt This stupid kaiku >>> f.close() # 3. readline >>> f = open(r'd:\sometext.txt') >>> for i in range(3): print str(i) + ': ' + f.readline(), 0: Welcome to this file 1: There is nothing here execpt 2: This stupid kaiku # 4. readlines >>> import pprint >>> pprint.pprint(open(r'd:\sometext.txt').readlines()) ['Welcome to this file\n', 'There is nothing here execpt\n', 'This stupid kaiku'] #写文件 >>> f = open(r'd:\sometext.txt', 'w') >>> f.write('this\nis no\nhaiku') >>> f.close() >>> print(open(r'd:\sometext.txt').read()) this is no haiku # writelines >>> f = open(r'd:\sometext.txt') >>> lines = f.readlines() >>> f.close() >>> lines[1] = 'isn\'t a\n' >>> f = open(r'd:\sometext.txt', 'w') >>> f.writelines(lines) >>> f.close() >>> print(open(r'd:\sometext.txt').read()) this isn't a haiku
3. 对文件内容进行迭代
-
按字节处理
# 使用while方法对每个字符进行循环 f = open(filename) while True: char = f.read(1) if not char: break process(char) f.close() # read在到达文件末尾时返回一个空字符串
-
按行处理
# 使用while方法对进行循环 f = open(filename) while True: line = f.readline() if not line: break process(line) f.close() # readline在到达文件末尾时返回一个空字符串
-
读取整个文件
如果文件不是很大,可以使用不带参数的read方法一次读取整个文件,或者使用readlines
#用read迭代每个字符 f = open(filename) for char in f.read(): process(char) f.close() #用readlines迭代行 f = open(filename) for line in f.readlines: process(line) f.close()
-
fileinput实现懒惰行迭代
import fileinput for line in fileinput.input(filename): process(line)
-
文件迭代器
-
python 2.2开始文件对象是可迭代的,可以直接在for循环中使用他们
for line in open(filename): process(line) #sys.stdin是可迭代的,如果要迭代标准输入的所有行 import sys for line in sys.stdin: process(line)
-