栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Python中修改大型文本文件的最后一行的最有效方法

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Python中修改大型文本文件的最后一行的最有效方法

更新:使用ShadowRanger的答案。它更短且更健壮。

对于后代:

读取文件的最后N个字节,然后向后搜索换行符。

#!/usr/bin/env pythonwith open("test.txt", "wb") as testfile:    testfile.write('n'.join(["one", "two", "three"]) + 'n')with open("test.txt", "r+b") as myfile:    # Read the last 1kiB of the file    # we could make this be dynamic, but chances are there's    # a number like 1kiB that'll work 100% of the time for you    myfile.seek(0,2)    filesize = myfile.tell()    blocksize = min(1024, filesize)    myfile.seek(-blocksize, 2)    # search backwards for a newline (excluding very last byte    # in case the file ends with a newline)    index = myfile.read().rindex('n', 0, blocksize - 1)    # seek to the character just after the newline    myfile.seek(index + 1 - blocksize, 2)    # read in the last line of the file    lastline = myfile.read()    # modify last_line    lastline = "Brand New Line!n"    # seek back to the start of the last line    myfile.seek(index + 1 - blocksize, 2)    # write out new version of the last line    myfile.write(lastline)    myfile.truncate()


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/645134.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号