小编Dov*_*iin的帖子

就地修改文本文件的最佳方法是什么?

如果已经有人问过类似的问题,我深表歉意——我确实搜索了一些东西,我可能错过了一些东西,但至少在我看来,其他问题的答案并不是我想做的事情。

我有一个包含以下信息的文本文件(我们称之为“Potatoes.txt”):

Town 1,300,
Town 2,205,
Town 3,600,
Town 4,910,
Town 5,360,
Run Code Online (Sandbox Code Playgroud)

我想做的是减少某些城镇的数量,并相应地修改文本文件。我做了一些研究,看起来你不能修改文本文件,我需要文本文件具有相同的名称,只是里面有不同的值,所以我目前正在这样做:

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)
Run Code Online (Sandbox Code Playgroud)

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

谢谢您的帮助。

python file in-place

6
推荐指数
2
解决办法
9925
查看次数

使用枚举的好处?

我是Python的初学者.我想知道列举一种更有效的方法吗?或者在这里没那么重要,而且只有在做更复杂的事情时才会发挥作用?

我的代码没有枚举:

for x in thing:
    if thing.index(x) % 2 == 0:
        x += 7
        print (x)
    else:
        print (x)
Run Code Online (Sandbox Code Playgroud)

和我的代码使用枚举:

for index,x in enumerate(thing):
    if index % 2 == 0:
        x += 7
        print (x)
    else:
        print (x)
Run Code Online (Sandbox Code Playgroud)

python

4
推荐指数
1
解决办法
558
查看次数

标签 统计

python ×2

file ×1

in-place ×1