[英]Loading the nth line of a txt file in python without loading the whole file
[英]How to change the nth byte in a file without loading it into RAM using Python
有什么方法可以更改空间和时间复杂度为 O(1) 的文件的第 n 个字节。 我确实知道一种以 O(n) 时间复杂度读取第 n 个字节(不加载到 RAM)的方法,方法是每 x 个字符添加一个换行符并遍历文件中的行。
注意:我有一个 .txt 文件,大小约为 1GB,使用 latin-1 编码(因此每个字符占用 1 个字节)。
正如评论中已经提到的,您可以将当前文件 position 更改为文件中的特定位置,然后您可以覆盖下一个字节。
with open("blankpaper.txt", "wb") as f:
# write a few bytes to file
f.write(b"abcdefg")
# changes file position
f.seek(3)
# overwrites the fourth byte
f.write(b"g")
生成的文件包含内容b"abcgefg"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.