You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python按指定词数限制保留文件末尾内容

问题解决更新

感谢各位的帮助,我终于搞定这个问题了!之前脑子一时卡壳,居然没用到这种思路,现在附上可用的代码。其他方案虽然能实现功能,但没法保留原文件的换行格式,这个方案可以做到。

可用代码

log_file = open("bigfile.txt", "rt")
contents = log_file.read()
words = contents.split(' ') #added space here
log_file.close() 

write_file = open("info.txt",'w') # 清空目标文件原有内容

# 截取文件末尾的内容
words_to_add = words[-1000:] # 参考@jpa的建议

for w in words_to_add:
    write_file.write(w + " ")

write_file.close()

内容的提问来源于stack exchange,提问作者Music lyric bot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 15:20:51