在python中更改文件的第一行 [英] change first line of a file in python

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

问题描述

我只需要读取一个大文件的第一行并更改它.

I only need to read the first line of a huge file and change it.

有什么技巧可以只更改文件的第一行并使用 Python 将其另存为另一个文件?我所有的代码都是用 Python 完成的,这有助于我保持一致性.

Is there a trick to only change the first line of a file and save it as another file using Python? All my code is done in Python and would help me to keep consistency.

这个想法是不必读取然后写入整个文件.

The idea is to not have to read and then write the whole file.

推荐答案

shutil.copyfileobj() 应该比逐行运行快得多.文档中的注释:

shutil.copyfileobj() should be much faster than running line-by-line. Note from the docs:

注意如果[from_file]对象的当前文件位置不为0,仅从当前文件位置到文件末尾的内容文件将被复制.

Note that if the current file position of the [from_file] object is not 0, only the contents from the current file position to the end of the file will be copied.

因此:

from_file.readline() # and discard
to_file.write(replacement_line)
shutil.copyfileobj(from_file, to_file)

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

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