在 Python 中的现有文件前添加一行 [英] Prepend a line to an existing file in Python

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

问题描述

我需要在文本文件的第一行添加一行,看起来我唯一可用的选项是比我对 python 期望的更多的代码行.像这样:

I need to add a single line to the first line of a text file and it looks like the only options available to me are more lines of code than I would expect from python. Something like this:

f = open('filename','r')
temp = f.read()
f.close()

f = open('filename', 'w')
f.write("#testfirstline")

f.write(temp)
f.close()

没有更简单的方法吗?此外,我看到这个双句柄示例比打开单个句柄进行读写 ('r+') 的频率更高 - 为什么会这样?

Is there no easier way? Additionally, I see this two-handle example more often than opening a single handle for reading and writing ('r+') - why is that?

推荐答案

Python 使很多事情变得简单,并包含用于许多常见操作的库和包装器,但目标不是隐藏基本事实.

Python makes a lot of things easy and contains libraries and wrappers for a lot of common operations, but the goal is not to hide fundamental truths.

您在这里遇到的基本事实是,您通常无法在不重写整个结构的情况下将数据添加到现有的平面结构中.无论语言如何,都是如此.

The fundamental truth you are encountering here is that you generally can't prepend data to an existing flat structure without rewriting the entire structure. This is true regardless of language.

有一些方法可以保存文件句柄或降低代码的可读性,其中许多方法在其他答案中提供,但都没有改变基本操作:您必须读入现有文件,然后写出要添加的数据,后跟您读入的现有数据.

There are ways to save a filehandle or make your code less readable, many of which are provided in other answers, but none change the fundamental operation: You must read in the existing file, then write out the data you want to prepend, followed by the existing data you read in.

无论如何都要保存文件句柄,但不要试图将这个操作打包成尽可能少的代码行.事实上,永远不要寻找最少的代码行——那是混淆,而不是编程.

By all means save yourself the filehandle, but don't go looking to pack this operation into as few lines of code as possible. In fact, never go looking for the fewest lines of code -- that's obfuscation, not programming.

这篇关于在 Python 中的现有文件前添加一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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