读文件
def read_file(filepath):
with open(filepath, 'r', encoding='utf-8') as file:
for line in file:
print(line)
写文件
def write_file(filepath):
with open(filepath, 'w', encoding='utf-8') as file:
file.write('hello world')
读写文件
def read_write_file(filepath):
with open(filepath, 'r+', encoding='utf-8') as file:
text = file.read()
# 处理文本
text = re.sub('python', 'python3', text)
# 默认是在最后追加,以下方法可覆盖
file.seek(0)
file.truncate()
# 写入
file.write(text)