文件的输入输出 file-io
关于文件的打开模式有以下标志,需牢记!!!
Python File(文件) 方法
file 对象使用 open 函数来创建,下图列出了 file 对象常用的函数:
In [0]: fo = open('/bao/file','wb')#打开文件
In [1]: fo.#文件操作的方法
fo.close fo.flush fo.next fo.seek fo.writelines
fo.closed fo.isatty fo.read fo.softspace fo.xreadlines
fo.encoding fo.mode fo.readinto fo.tell
fo.errors fo.name fo.readline fo.truncate
fo.fileno fo.newlines fo.readlines fo.write
In [2]: fo.name#获取文件的名称
Out[2]: '/bao/file'
In [3]: fo.closed#判断文件是否关闭
Out[3]: False
In [4]: fo.mode#获取文件的访问模式
Out[4]: 'wb'
In [5]: fo.softspace#判断末尾是否强制加空格
Out[5]: 0
In [6]: fo.close()#关闭文件
In [7]: fo.closed#判断文件是否关闭
Out[7]: True
In [10]: fo.write('halo')#向文件中追加内容,如果不关闭的话内容还在缓存中,需要关闭文件或者使用flush方法使内容保存到文件中去
In [11]: fo.flush()#缓存写入
In [12]: fo.tell()#获取文件当前位置
Out[12]: 10
In [13]: fo.seek(5)#将指针定位到文件的某个位置
In [14]: fo.tell()
Out[14]: 5
In [98]: fo.read()#读取文件的内容,默认读取最大能读取的字节数,并且将操作指针移到最大字节处
Out[98]: 'halosdfsdfsdf\nsfdsfsdff\nsdfdsf\naaaaaaaaaaaaddddddddddddddddddsffsdf'
In [99]: fo.read(10)#因为上一个操作已经将文件指针移到文件末尾,所以没有剩余内容可以读取
Out[99]: ''
In [100]: fo.tell()#获取当前文件操作指针的位置
Out[100]: 67
In [101]: fo.seek(0)#将文件操作指针重新定位到文件开头,然后再去读取就OK了
In [102]: fo.read(10)#从文件操作指针出开始读取10个字节的内容
Out[102]: 'halosdfsdf'
In [109]: cat /bao/file
halosdfsdfsdf
sfdsfsdff
sdfdsf
aaaaaaaaaaaaddddddddddddddddddsffsdf
In [106]: fo.readline()#按行读取文件,再次操作的时候读取下一行,类似生成器
Out[106]: 'halosdfsdfsdf\n'
In [107]: fo.readline()
Out[107]: 'sfdsfsdff\n'
In [108]: fo.readline()
Out[108]: 'sdfdsf\n'
In [109]: fo.readline()
Out[109]: 'aaaaaaaaaaaaddddddddddddddddddsffsdf'
In [110]: fo.readline()
Out[110]: ''
In [114]: fo.readlines()#默认一次读取尽可能多的行返回一个列表存储所有的行,每一个行作为一个列表的元素;如果传递一个整形参数的话就读取指定大小的内容后返回,这样可以避免大文件读取造成的内存占用
Out[114]:
['halosdfsdfsdf\n',
'sfdsfsdff\n',
'sdfdsf\n',
'aaaaaaaaaaaaddddddddddddddddddsffsdf']
In [122]: fo = open('/bao/file')
In [123]: p = fo.xreadlines()#获得一个文件读取的迭代对象
In [124]: p.next()#调用迭代对象逐个获取文件行
In [19]: from collections import Iterable
In [20]: isinstance(fo,Iterable)#判断文件对象是可迭代的
Out[20]: True
In [21]: for i in fo:
....: print i
....:
daemon:x:2:2:daemon:/sbin:/sbin/nologin
#with 语句是从 Python 2.5 开始引入的一种与异常处理相关的功能,可以用来安全打开一个文件
In [29]: with open('/bao/file','r') as fo:
....: print fo.read()
....:
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
练习
1. 过滤掉文件中以#开头的行:
def fileFilter(fname):
fo = open(fname,'r+')
while True:
line = fo.readlines(2)
if not line:
break
else:
for i in line:
stripLine = i.strip()
if not stripLine.startswith('#'):
print stripLine
fo.close()
2.根据用户输入的读取行数,然后判断用户的读取行为(继续还是退出)来显示文本中每一次读取的内容:
def fileRead():
while True:
filename = raw_input('Please input file name(q to quit): ')
if filename in 'qQ':
return
try:
fo = open(filename,'r')
lines = raw_input('Please input read lines(q to quit): ')
if lines in 'qQ':
return
try:
lines = int(lines)
print '1-%s lines contents as below:\n'%lines
for i in range(0, lines):
print fo.readline().strip()
times = 0
while True:
ynq = raw_input('\nSure to continue read file content[y/n]:')
if ynq in 'nN':
return
if ynq in 'yY':
if not fo.readline():
print 'File read to the end!'
return
times += 1
starts = lines * times
ends = starts + lines
print '{}-{} lines contents as below:\n'.format(starts + 1, ends)
for i in range(starts, ends):
print fo.readline().strip()
fo.close()
except:
print 'Illegal line number!'
except:
print 'No such file or permission denied!'