如何修改文本文件? [英] How to modify a text file?

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

问题描述

我使用的是Python,并且希望将文本文件中的字符串插入到文本文件中,而不会删除或复制文件。如何做到这一点?

I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?

推荐答案

不幸的是没有办法插入文件的中间而不重写。如以前的海报所示,您可以使用搜索附加到文件或覆盖其中的一部分,但如果要在开头或中间添加内容,则必须重写。

Unfortunately there is no way to insert into the middle of a file without re-writing it. As previous posters have indicated, you can append to a file or overwrite part of it using seek but if you want to add stuff at the beginning or the middle, you'll have to rewrite it.

这是一个操作系统的东西,而不是Python的东西。在所有语言中都是一样的。

This is an operating system thing, not a Python thing. It is the same in all languages.

我通常做的是从文件中读取,进行修改并将其写入一个名为myfile.txt.tmp的新文件或类似的东西。这比把整个文件读入内存要好,因为文件可能太大了。一旦临时文件完成,我将其重命名与原始文件相同。

What I usually do is read from the file, make the modifications and write it out to a new file called myfile.txt.tmp or something like that. This is better than reading the whole file into memory because the file may be too large for that. Once the temporary file is completed, I rename it the same as the original file.

这是一个很好的安全方法,因为如果文件写入崩溃或中止由于任何原因,您仍然拥有未经修改的原始文件。

This is a good, safe way to do it because if the file write crashes or aborts for any reason, you still have your untouched original file.

这篇关于如何修改文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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