就地修改文本文件的最佳方法是什么? [英] What is the best way to modify a text file in-place?

查看:63
本文介绍了就地修改文本文件的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,是否已经提出类似的要求-我确实搜索了一下,可能错过了一些内容,但是在我看来,至少其他问题的答案与我想要的东西不完全相同要做.

Apologies if something similar has already been asked - I did search around a bit, and I probably missed something, but it seems to me at least that the answers for other questions weren't really about the same thing I'm wanting to do.

我有一个文本文件,(将其称为"Potatoes.txt")包含以下信息:

I have a text file, (let's call it 'Potatoes.txt') containing the following info:

Town 1,300,
Town 2,205,
Town 3,600,
Town 4,910,
Town 5,360,

我想做的是减少某些城镇的数量,并相应地修改文本文件.我做了一些研究,发现您无法修改文本文件,并且我需要文本文件具有相同的名称,只是其中具有不同的值,所以我目前正在这样做:

What I want to do is decrease the number for certain towns, and modify the text file accordingly. I did a little research and it appears you can't modify text files, and I need the text file to have the same name, just have different values inside it, so I'm currently doing this instead:

f = open("ModifiedPotatoes.txt","w")
f.close()

with open("Potatoes.txt","r") as file:
    for line in file:
       info = line.split(",")
       if "Town 2" or "Town 4" in line:
           info[1] -= 20
       with open("ModifiedPotatoes.txt","a"):
           infoStr = "\n" + ",".join(str(x) for x in info)
           file.write(infoStr)

f = open("Potatoes.txt","w")
f.close()

with open("ModifedPotatoes.txt","r") as file:
    for line in file:
        with open("Potatoes.txt","a") as potatoesFile:
            potatoesFile.write(line)

因此,基本上,我只是将旧文件覆盖为空白文件,然后从修改后的/临时文件中复制值.有没有更好的方法可以做到这一点?

So basically I'm just overwriting the old file to a blank one, then copying the value from the modified / temporary file. Is there a better way to do this I'm missing?

感谢您的帮助.

推荐答案

我做了一些研究,看来您无法修改文本文件

I did a little research and it appears you can't modify text files

有一个模块,当您在其上循环时,具有与修改文本相同的效果.尝试将 fileinput 模块与 inplace 选项设置为 True .

There is a module that gives you the same effect as modifying text as you loop over it. Try using the fileinput module with the inplace option set to True.

以下是一些Python3.6代码,可以帮助您入门:

Here is a little Python3.6 code to get you started:

from fileinput import FileInput

with FileInput(files=['Potatoes.txt'], inplace=True) as f:
    for line in f:
        line = line.rstrip()
        info = line.split(",")
        if "Town 2" in line or "Town 4" in line:
            info[1] = int(info[1]) - 20
            line = ",".join(str(x) for x in info))
        print(line)

这篇关于就地修改文本文件的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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