如何写入文件的特定行? [英] How to write to a specific line of a file?

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

问题描述

假设我有一个文本文件

Line 1
Line 2
Line 3

我仔细阅读了一下,决定将2号线更改为2号线.我可以用Python优雅地做到这一点,而不必简​​单地用更改来重写文件吗?我尝试使用file.seek(),但它并没有真正实现任何目的,也不了解它的确切作用.

I read through it and decide to change Line 2 to Line Two. Can I do that elegantly in Python without simply rewriting the file with the changes? I tried with file.seek() but I didn't really get anywhere with it nor I understand what it does exactly.

推荐答案

文件是字节序列.如果要在中间更改需要更多或更少字节表示的内容,则文件的其余部分需要调整大小.

A file is a sequence of bytes. If you want to change something in the middle that requires more or fewer bytes to express, the rest of the file needs to resize.

因为文件是存储介质上的物理字节序列,所以这意味着您需要重写文件的整个 rest .换句话说,您需要移至line 2之后的所有内容.

Because a file is a physical sequence of bytes on a storage medium, that means you need to rewrite the entire rest of the file. In other words, you need to move over everything following line 2.

实际上,这意味着重写文件,因为这很容易实现.

In practice, that means rewriting the file, as that is much easier to achieve.

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

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