1.打开/关闭文件python
首先来看一下Python中的open函数:缓存
open(file, mode='r', buffering=-1, encoding=None)函数
1)file: 文件名编码
2)mode: 这个跟标准c库中fopen中的mode参数取值相似:spa
'r': 以只读方式打开文件,若是文件不存在,则会抛出IOErrorcode
‘w': 以只写方式打开文件,若是文件不存在,则会自动建立文件;若是文件已经存在,则会清空文件已有的内容内存
'a': 以追加的方式打开,通常会与'w'联合使用;utf-8
'b': 二进制模式打开,表示此文件中的数据不是文本数据;it
'+': 读/写模式, 'r+':表示读写方式打开文件,'w+'以读写方式打开文件;for循环
4)buffering: 表示是否使用缓存,若是使用缓存的话,咱们往文件中写入数据时,并不会立刻写入到文件中,而是写入到缓存中,直至咱们flush()或者close()时,才会把缓存中的数据写入到文件中;
5)encoding: 指定写入字符的编码,如utf-8
open函数若是成功,则会返回一个file object,不然返回None.
关闭文件: close()函数
f = open(file='data.txt', mode='w+', encoding='utf-8') if f: print('open %s success' % f.name) f.close() else: print('open failed') >>> open data.txt success
2.读写文件
在open成功后,会返回一个file object,文件的读写函数,就是调用file object中的读写函数来完成的。
1)write(str): 把str写入到文件中
2)writelines(seq): 把序列中的每个元素依次写入到文件中,注意每一个元素直接并不会自动插入换行符file.linesep
3)read(): 返回整个文件的数据
4)readline(): 返回文件中的一行数据
5)readlines(): 以list的方式返回文件中的每一行数据,注意每一行的换行符并无去除
6)read(nums): 读取指定nums个字符
当已读取到EOF时,会返回None。
#写入文件 f = open(file='data.txt', mode='w', encoding='utf-8') if f: print('open %s success' % f.name) f.write('hello Python\n') lines = ('hello\n', 'world') f.writelines(lines) f.close() else: print('open failed')
#读取文件 try: f = open('data.txt') print(f.readlines()) except IOError: print('file IOError') finally: f.close() >>> ['hello Python\n', 'hello\n', 'world']
若是文件比较大,调用read()或者readlines()一次性把全部的数据读取到内存中,会占用较大的内容空间,因此通常的建议是一部分一部分的读取:
#循环读取并处理 try: f = open('data.txt') while True: line = f.readline() if line: print(line) else: break except IOError: print('file IOError') finally: f.close() >>> hello Python hello world
在上面的代码中,咱们发现每次都要在finally中加入f.close(),比较麻烦,因此Python在2.5以后,引入with语句:能够自动帮助咱们在语句结束后关闭文件,即便是异常引发的结束:
with open('data.txt') as f: while True: line = f.readline() if line: print(line) else: break
3.文件迭代器
在Python2.2开始,file object是能够迭代的,这意味着能够直接在for循环中使用。
#iteraing file object with open('data.txt') as f: for line in f: print(line)
执行后的输出与上面同样,可是代码显得更加的简洁。
file object还有seek, trunscate, flush等方法,这些方法都是跟c标准库中的方法对应的。