如何在用python重写行之前删除以前版本的行
我正在尝试更改文本文件中的某些信息。最初,文本文件看起来像如何在用python重写行之前删除以前版本的行,python,Python,我正在尝试更改文本文件中的某些信息。最初,文本文件看起来像 Entertainment 70 Clothing 15 Food 25 运行这个程序之后 import os, sys import cs50 from cs50 import get_int def main(): print("Welcome to the money tracker program!") SpentOnEntertainment = get_int("Ho
Entertainment
70
Clothing
15
Food
25
运行这个程序之后
import os, sys
import cs50
from cs50 import get_int
def main():
print("Welcome to the money tracker program!")
SpentOnEntertainment = get_int("How much money do you plan on spending on Entertainment? ")
SpentOnClothing = get_int("How much money do you plan on spending on Clothing? ")
SpentOnFood = get_int("How much money do you plan on spending on Food? ")
Textfile = open("AFile2.txt", "r+")
currentfunds = Textfile.readlines()
if(SpentOnEntertainment > int(currentfunds[1])):
print("Sorry, you can only spend", currentfunds[1], "dollars on Entertainment.")
SpentOnEntertainment = int(currentfunds[1])
currentfunds[1] = str(int(currentfunds[1]) - SpentOnEntertainment) + "\n"
if(SpentOnClothing > int(currentfunds[3])):
print("Sorry, you can only spend", currentfunds[3], "dollars on Clothing.")
SpentOnClothing = int(currentfunds[3])
currentfunds[3] = str(int(currentfunds[3]) - SpentOnClothing) + "\n"
if(SpentOnFood > int(currentfunds[5])):
print("Sorry, you can only spend", currentfunds[5], "dollars on Food.")
SpentOnFood = int(currentfunds[5])
currentfunds[5] = str(int(currentfunds[5]) - SpentOnFood) + "\n"
Textfile.writelines(currentfunds)
sys.exit(0)
if(__name__ == "__main__"):
main()
这允许用户选择他们想要花多少钱,从而改变剩余的钱,新行被附加到我的原始行的末尾,我的最终结果(文本文件)是
我怎样才能摆脱前6行,因为它们不再相关?我尝试过在重读列表后使用诸如删除项目[0:6]之类的方法,但没有任何效果。最简单的方法(我认为是)就是打开文件
读取文件并保存行
然后清空文件
Textfile = open("AFile2.txt", "r+") # open file
currentfunds = list(Textfile.readlines()) #save the lines
Textfile.close() #close the file
open('AFile2.txt', 'w').close() #empty the file
Textfile = open("AFile2.txt", "r+") # re-open file
谢谢,是的,我以w的形式再次打开文件,解决了这个问题+
Textfile = open("AFile2.txt", "r+") # open file
currentfunds = list(Textfile.readlines()) #save the lines
Textfile.close() #close the file
open('AFile2.txt', 'w').close() #empty the file
Textfile = open("AFile2.txt", "r+") # re-open file