- 解决Python对文件读、写、追加、大文件读、换行处理等问题
import os
txt_list = ['你好', '2020', 'hi']
file_path = 'test.txt'
with open(file_path, 'w', encoding='utf-8') as f_w:
for i, v in enumerate(txt_list):
txt = f'{v}\n' if i < len(txt_list) - 1 else v
f_w.write(txt)
print(f"写:{i}行:" + v.replace('\n', ''))
with open(file_path, 'r', encoding='utf-8') as f_r:
lines = f_r.readlines()
for i, v in enumerate(lines):
print(f"读:{i}行:" + v.replace('\n', ''))
txt_append_list = ['追加1', '追加2', '追加3']
with open(file_path, 'a+', encoding='utf-8') as f_a:
f_a.seek(0, 0)
if f_a.readline():
f_a.write('\n')
for i, v in enumerate(txt_append_list):
txt = f'{v}\n' if i < len(txt_append_list) - 1 else v
f_a.write(txt)
print(f"追加写:" + txt.replace('\n', ''))
def tail(path, n=10):
f_size = os.path.getsize(path)
block_size = 1024*n
last_line = ""
with open(path, 'r', encoding='utf-8') as f_r:
if f_size > block_size:
max_seek_point = (f_size // block_size)
f_r.seek((max_seek_point - 1) * block_size)
elif f_size:
f_r.seek(0, 0)
lines = f_r.readlines()
if lines:
last_line = lines[-n:]
return last_line
print(f'倒数两行:{tail(file_path, 2)}')