有效的方法来改变Python中的文件头 [英] efficient way to change the header of a file in Python

查看:116
本文介绍了有效的方法来改变Python中的文件头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个python脚本来更新一些大文件的头文件(只有第一行),但是由于新头文件并不需要与原文件大小相同(以字节为单位),无论如何,我可以更改标题,而不必接触其他巨大的文件?或者我必须通读它们并将它们写回到文件中?解析方案

不,您可以在文件上执行的唯一操作无需触及整个文件即可截断替换相同的大小,然后追加。

您可以,但是,在读取当前驻留在新位置的所有数据之后,缓冲文件的相对较小的部分并写入,以避免内存耗尽。如果速度有问题,请考虑使用 mmap


I am trying to write a python script to update the header (only the first line) of some huge files, but as the new header is not necessary to be the same size (in bytes) as the original one, is there anyway I could change the header without touching the rest of the huge file? or I have to read through them all and write them back to file?

解决方案

No, the only operations you can do on files without touching the whole file are truncation, replacement of same size, and appending.

You can, however, buffer relatively small parts of the file and write them after you've read all data currently residing in the new position, to avoid memory exhaustion. If speed is an issue, consider using mmap.

这篇关于有效的方法来改变Python中的文件头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆