我有一个文本文件(我们称之为“Potatoes.txt”),其中包含以下信息:
Town 1,300,
Town 2,205,
Town 3,600,
Town 4,910,
Town 5,360,
我想做的是减少某些城镇的数量,并相应地修改文本文件。经过一些研究,我发现无法直接修改文本文件,而我需要保持文本文件名称不变,只是里面的值不同,因此我目前正在尝试以下方法:
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)
基本上,我只是用一个空文件覆盖旧文件,然后将修改/临时文件中的值复制过来。我有没有漏掉更好的方法?
with open("ModifedPotatoes.txt","r") as file:
中使用w
而不是r
。 - Aidenhjj