读和写文件
open()将会返回一个file对象,基本语法如下:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
mode参数的定义可以看下面这张表
、
模式 | r | r+ | w | w+ | a | a+ |
读 | + | + | + | + | ||
写 | + | + | + | + | ||
创建 | + | + | + | + | ||
覆盖 | + | + | ||||
指针在开头 | + | + | + | + | ||
指针再末尾 | + | + |
举几个例子:
#读取文件
f1 = open("/Users/ace/PycharmProjects/pythonSt/a.txt","r")
f1.readlines 读取多行
f1.readline 读取单行
for x in f1:
print(f1)
- file: 必需,文件路径(相对或者绝对路径)。
- mode: 可选,文件打开模式
- buffering: 设置缓冲
- encoding: 一般使用utf8
- errors: 报错级别
- newline: 区分换行符
- closefd: 传入的file参数类型
- opener:
f.seek() 类似java中的RandomAccessFile 移动指针位置
f.tell() 方法, 来确定 文件流的位置
pickle 模块
类似java中的对象流,把对象写入文件中
完整例子
import pickle
data1 = {'a': [1, 2.0, 3, 4+6j],
'b': ('string', u'Unicode string'),
'c': None}
output = open('data.pkl', 'wb')
pickle.dump(data1,output) //把对象写入文件中
output.close()
intput = open('data.pkl','rb')
print(pickle.load(intput)) //把对象从文件中读取出来
==================================华丽的分割线==========================================
下面这个例子说明了异常中的所有关键字
for x in [1,2,3,4,"12fdsfds"]:
try:
int(x)
except ValueError:
print("发生错误")
except (NameError,RuntimeError,TypeError):
print("其他错误")
except:
pass
else://没有发生异常时候执行
print("no exption")
finally://无论如何都会执行。和java类似
print("all")
with open("myfile.txt") as f:
for line in f:
print(line)
with 语句使得文件之类的对象可以 确保总能及时准确地进行清理。
语句执行后,文件 f 总会被关闭,即使是在处理文件中的数据时出错也一样。其它对象是否提供了预定义的清理行为要查看它们的文档。