Python:读取一行并写回同一行 [英] Python: read a line and write back to that same line

查看:371
本文介绍了Python:读取一行并写回同一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python制作html的模板更新程序.我读了一行并将其与模板文件进行比较,以查看是否有任何需要更新的更改.然后,我想将所有更改(如果有的话)写回到我刚刚读取的同一行.

I am using python to make a template updater for html. I read a line and compare it with the template file to see if there are any changes that needs to be updated. Then I want to write any changes (if there are any) back to the same line I just read from.

读取文件后,我的文件指针现在位于readline()之后的下一行.反正我可以写回同一行而不必打开两个文件句柄进行读写了吗?

Reading the file, my file pointer is positioned now on the next line after a readline(). Is there anyway I can write back to the same line without having to open two file handles for reading and writing?

这是我要执行的操作的代码段:

Here is a code snippet of what I want to do:

cLine = fp.readline()
if cLine != templateLine:
   # Here is where I would like to write back to the line I read from
   # in cLine

推荐答案

在文本文件中更新行-非常困难

SO中的许多问题都试图读取文件并立即对其进行更新.

Updating lines in place in text file - very difficult

Many questions in SO are trying to read the file and update it at once.

尽管这在技术上是可行的,但这是非常困难的.

While this is technically possible, it is very difficult.

(文本)文件不是按行组织在磁盘上的,而是按字节组织的.

(text) files are not organized on disk by lines, but by bytes.

问题是,旧行上的读取字节数通常与新行上的字节数不同,这会弄乱生成的文件.

The problem is, that read number of bytes on old lines is very often different from new one, and this mess up the resulting file.

虽然听起来效率低下,但从编程角度来看,这是最有效的方法.

While it sounds inefficient, it is the most effective way from programming point of view.

仅从一侧读取文件,在另一侧写入另一个文件,关闭文件,然后从旧文件中复制新创建的内容.

Just read from file on one side, write to another file on the other side, close the files and copy the content from newly created over the old one.

或者在内存中创建文件,并在关闭旧文件后最后重写旧文件.

Or create the file in memory and finally do the writing over the old one after you close the old one.

这篇关于Python:读取一行并写回同一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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