1.打开文件
f = open('db','a')#追加 f = open('db','w')#只写,先清空原文件 f = open('db','r')#只读 f = open('db','x')#文件存在,报错,不存在,创建并写内容 f = open('db','r',encoding='utf-8')#出现encoding时编码错误(平常用utf-8)
如果加b时读取的是字节(写入时需要转换成字节+编码写入)
如果参数后带+号表示可读可写
例:不加b的情况下输出文件(类型为字符串str形式)
f = open('db','r',encoding='utf-8') data = f.read() print(data,type(data)) f.close() --------------结果---------------- /usr/bin/python3.5 /home/liangml/pythonscript/test.py 123 tony <class 'str'>
加b的情况下输出的文件(类型为字节的形式bytes)
f = open('db','rb',encoding='utf-8')#只要是加b的直接写入字节(都是二进制的) data = f.read() print(data,type(data))
------------------------------------------------
# f = open('db','ab')
# f.write(bytes("hello",encoding="utf-8"))#写入是转换成字节
# f.close()
----------------结果-------------- /usr/bin/python3.5 /home/liangml/pythonscript/test.py b'123 tony ' <class 'bytes'>
#如果有加号则表示可读可写
f = open('db','r+',encoding='utf8') #如果模式无b,则read,按照字符读取 data = f.read() print(data) print(f.tell())#获取当前指针的位置 f.seek(1)#主动的调整指针的位置(但是会覆盖) f.write('777') f.close()
2.操作文件
read()#无参数,读全部;有参数 1.b,按字节 2.无b,按字符 tell()获取当前指针的位置 seek(1)指针跳转到指定的位置(字节) write()写数据,b,字节;无b,字符 fileno文件描述符 flush强刷 readable查看是否可读 wirteable查看是否可写 readline 仅读取一行 truncate 截断数据,指针位置后的清空 for循环文件对象 f = open(xxx) f = open('db','r+',encoding='utf8') for line in f: print(line)
3.关闭文件
1.可以通过close来关闭文件
2.可以通过with方式来关闭文件(with可以同时打开多个文件)
close方式关闭
f.close() with open('db') as f: pass
with方式来关闭
with open('db') as f: pass with open('db','r',encoding='utf-8') as f1,open('db2','w',encoding='utf-8') as f2:#可以同时打开多个文件 times = 0 for line in f1: times += 1 if times <=10: f2.write(line) else: break with open('db','r',encoding='utf-8') as f1,open('db2','w',encoding='utf-8') as f2: for line in f1: new_str = line.replace('liangml','st')#replace更换 f2.write(new_str)