标签:文件内容 rename byte 平台 管理 字节 其他 读一行 二进制格式
f = open(‘a.txt‘, encoding=‘utf-8‘) data = f.read() print(data) print(‘data2------------->‘) data2 = f.read() print(data2) 运行结果: hello,world. what is your name? how are you? data2------------->
import os read_f = open(‘a.txt‘, ‘r‘, encoding=‘utf-8‘) write_f = open(‘b.txt‘, ‘w‘, encoding=‘utf-8‘) for line in read_f.readlines(): if line.startwith(‘4444444444‘): line = ‘dddddddddddd\n‘ write_f.write(line) read_f.close() write_f.close() os.remove(‘a.txt‘) os.rename(‘b.txt‘, ‘a.txt‘)
with open(‘a.txt‘, ‘rb‘) as f: print(f.read()) 运行结果: b‘\xe4\xbd\xa0\xe6\x98\xaf\xe8\xb0\x81‘ with open(‘a.txt‘, ‘rb‘) as f: print(f.read().decode(‘utf-8‘)) 运行结果: 你好
with open(‘c.txt‘, ‘wb‘) as f: f.write(‘你好吗‘.encode(‘utf-8‘))
查看c.txt文件内容为‘你好吗’
f = open(‘a.txt‘, encoding=‘utf-8‘) data = f.read() print(data) print(‘data2------------->‘) f.seek(0) data2 = f.read() print(data2) 运行结果: hello,world. what is your name? how are you? data2-------------> hello,world. what is your name? how are you?
f.seek(2, 1):代表以当前光标所在的位置开始,往后移动2个bytes,仅在b模式打开时可用
with open(‘c.txt‘, ‘r+‘, encoding=‘utf-8‘) as f: f.truncate(3) 运行结果: 查看c.txt文件内容 你
import time with open(‘access.log‘, ‘r‘, encoding=‘utf-8‘) as f: f.seek(0, 2) while True: line = f.readline().strip() if line: print(‘新增:‘, line) time.sleep(1)
标签:文件内容 rename byte 平台 管理 字节 其他 读一行 二进制格式
原文地址:http://www.cnblogs.com/xiaofeiweb/p/6862892.html