【发布时间】:2021-07-19 00:49:08
【问题描述】:
我还是 python 新手,我已经尝试过这种方式来覆盖 txt 文件中的一行
'''
answer =input("R/S/L/M:")
if answer == "R":
print ("Racer")
f=open('character.txt', 'w+')
with open("character.txt") as file_in:
lines = [1]
for line in file_in:
lines.append(line)
amount=int(input("please enter the amount"))
f.write(answer )
f.write("" + "-" + str(amount) + '\n\n')
f.write("" + '\n')
f.close()
elif answer == "S":
print ("Sage")
f=open('character.txt', 'w+')
with open("character.txt") as file_in:
lines = [3]
for line in file_in:
lines.append(line)
amount=int(input("please enter the amount"))
f.write(answer )
f.write("" + "-" + str(amount) + '\n\n')
f.write("" + '\n')
f.close()
'''
它会替换所有文本行,无论 txt 文件如何 我要做的是,当我选择 R 时,它会写入 txt 文件的第一行,而当我选择 S 时,它会写入 txt 文件的第三行
我已经试过了
'''
if answer == "R":
print ("Racer")
f=open('character.txt', 'w+')
with open("character.txt", "r+") as myfile:
data = myfile.read()
myfile.seek(0)
amount=int(input("please enter the amount"))
newData1=(answer + "" + "-" + str(amount) + '\n\n')
myfile.write(newData1)
myfile.truncate()
f.close()
elif answer == "S":
print ("Sage")
f=open('character.txt', 'w+')
with open("character.txt", "r+") as myfile:
data = myfile.read(4)
myfile.seek(4)
amount=int(input("please enter the amount"))
newData2=(answer + "" + "-" + str(amount) + '\n\n')
myfile.write(newData)
myfile.truncate(4)
f.close()
'''
谁能指点我正确的方向
【问题讨论】:
-
您到底想达到什么目的?每次放置新值时,程序都会覆盖 .txt 文件中的行。您是否试图找到不覆盖文件的方法?
-
嗨 - 请您提供您正在寻找的文件输出示例,以及代码当前正在执行的操作的示例。
-
@tamerjar 我正在尝试拥有它,所以当我选择 S 或 R 并且当我输入所选数量时,它将覆盖它们所在的当前行并保留其他行未编辑这方面的一个例子是 txt 文档 S 位于第 3 行,所以当我在程序中选择 S 并输入金额时,它会用新的金额覆盖第 3 行
-
@Cerberton 目前我正在尝试获取它,所以当我选择 s 作为选项并选择我要添加的数量时,例如 S,10,我希望它覆盖第 3 行txt 文件,但是发生了什么,当我在此程序中选择 S 或其他选项时,它会覆盖 txt 文件中的所有数据。
标签: python python-3.x txt