标签:ace 文件 ble odi new var display 路径 lin
obj = open(‘路径‘,mode=‘模式‘,encoding=‘编码‘)
obj.write() # 写入
obj.read() # 读取
obj.close() #关闭
r / w / a 【只读只写字符串】 *
r+ / w+ / a+ 【可读可写字符串】
rb / wb / ab 【只读只写二进制】 *
r+b / w+b / a+b 【可读可写二进制】
read() , 全部读到内存
read(1)
1表示一个字符
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(字符串)
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)
?
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)
标签:ace 文件 ble odi new var display 路径 lin
原文地址:https://www.cnblogs.com/dpsy921/p/11179990.html