可能有的时候有人会在想为何要对文件进行操做,不管对于文件仍是网络之间的交互,咱们都是创建在数据之上的,若是咱们没有数据,那么不少的事情也就不可以成立,好比咱们淘宝买了一件衣服,那么淘宝是如何知道咱们的相关信息的呢?为何不会把咱们的衣服发给别人呢?这些都基于咱们自己的数据。而咱们的数据通常都存放在哪呢?python
在咱们没有接触数据库以前,咱们得到数据的手段也只能是从文件中获取,所以Python中的文件操做也是十分的重要。linux
操做文件时,通常须要经历以下步骤数据库
read() , 所有读到内存windows
read(1)网络
1表示一个字符code
obj = open('a.txt',mode='r',encoding='utf-8') data = obj.read(1) # 1个字符 obj.close() print(data)
1表示一个字节内存
obj = open('a.txt',mode='rb') data = obj.read(3) # 1个字节 obj.close()
write(字符串)utf-8
obj = open('a.txt',mode='w',encoding='utf-8') obj.write('中午你') obj.close()
write(二进制)资源
obj = open('a.txt',mode='wb') # obj.write('中午你'.encode('utf-8')) v = '中午你'.encode('utf-8') obj.write(v) obj.close()
seek(光标字节位置),不管模式是否带b,都是按照字节进行处理。字符串
obj = open('a.txt',mode='r',encoding='utf-8') obj.seek(3) # 跳转到指定字节位置 data = obj.read() obj.close() print(data) # rb模式 obj = open('a.txt',mode='rb') obj.seek(3) # 跳转到指定字节位置 data = obj.read() obj.close() print(data)
tell(), 获取光标当前所在的字节位置
obj = open('a.txt',mode='rb') # obj.seek(3) # 跳转到指定字节位置 obj.read() data = obj.tell() print(data) obj.close()
flush,强制将内存中的数据写入到硬盘
v = open('a.txt',mode='a',encoding='utf-8') while True: val = input('请输入:') v.write(val) v.flush() v.close()
v = open('a.txt',mode='a',encoding='utf-8') v.close()
with open('a.txt',mode='a',encoding='utf-8') as v: data = v.read() # 缩进中的代码执行完毕后,自动关闭文件
with open('a.txt',mode='r',encoding='utf-8') as f1: data = f1.read() new_data = data.replace('飞洒','666') with open('a.txt',mode='w',encoding='utf-8') as f1: data = f1.write(new_data)
f1 = open('a.txt',mode='r',encoding='utf-8') f2 = open('b.txt',mode='w',encoding='utf-8') for line in f1: new_line = line.replace('大大','小小') f2.write(new_line) f1.close() f2.close()
with open('a.txt',mode='r',encoding='utf-8') as f1, open('c.txt',mode='w',encoding='utf-8') as f2: for line in f1: new_line = line.replace('阿斯', '死啊') f2.write(new_line)
with open('log','r') as f: ...
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:
with open('log1') as obj1, open('log2') as obj2: pass