python读取一行返回的类型_Python:读取一行并写回同一行

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.

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

解决方案

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.

Update by creating a new 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值