如何在不删除原始内容的情况下在文本文件中的特定位置写入? [英] How to write at a particular position in text file without erasing original contents?

查看:63
本文介绍了如何在不删除原始内容的情况下在文本文件中的特定位置写入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 Python 编写了一个代码,它遍历文件,提取所有数字,然后将它们相加.我现在必须在文件中的特定位置写入总计"(一个整数),表示 something something something...Total: __00__ something something.

I've written a code in Python that goes through the file, extracts all numbers, adds them up. I have to now write the 'total' (an integer) at a particular spot in the file that says something something something...Total: __00__ something something.

我必须在 Total: __ 部分之后写出我计算的总数,这意味着结果行将更改为,例如:something something something...Total:__35__某事.

I have to write the total that I have calculated exactly after the Total: __ part which would mean the resulting line would change to, for example: something something something...Total: __35__ something something.

到目前为止,我有这个用于写入部分:

So far I have this for the write part:

import re
f1 = open("filename.txt", 'r+')
for line in f1:
    if '__' in line and 'Total:' in line:
        location = re.search(r'__', line)
print(location)

这会打印出:<_sre.SRE_Match object;span=(21, 23), match='__'>

所以它在位置 21 到 23 处找到了__",这意味着我想在位置 24 处插入总数.我知道我必须以某种方式使用 seek() 方法来做到这一点.但是我试过几次都失败了.任何建议将不胜感激.

So it finds the '__' at position 21 to 23, which means I want to insert the total at position 24. I know I have to somehow use the seek() method to do this. But I have tried and failed several times. Any suggestions would be appreciated.

重要提示:文件的原始内容将按原样保留.只有总的变化——没有别的.

Important: The original contents of the file are to be preserved as it is. Only the total changes -- nothing else.

推荐答案

如果文件不是特别大,可以将其在内存中的内容以字符串(或行列表)的形式读取,进行替换并写入内容背部.像这样:

If the file is not particularly large, you can read its contents in memory as a string (or a list of lines), do the replacement and write the contents back. Something like this:

total = 'Total: __{}__'.format(12345)

with open(filename, 'r+') as f:
    contents = f.read().replace('Total: __00__', total)
    f.seek(0)
    f.truncate()
    f.write(contents)

这篇关于如何在不删除原始内容的情况下在文本文件中的特定位置写入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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