Python 读写文件极简教程

  • 解决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)}')


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值