python:如何使用输入更改.txt文件中的字符串
所以我被这段代码困住了,关键是你们要输入车名和你们想租的车的数量,但我能想出在你们租完车后如何改变.txt文件中的字符串python:如何使用输入更改.txt文件中的字符串,python,arrays,string,file,Python,Arrays,String,File,所以我被这段代码困住了,关键是你们要输入车名和你们想租的车的数量,但我能想出在你们租完车后如何改变.txt文件中的字符串 def rental(): with open('cars.txt', 'r') as file: # cars.txt example: # bmw:320:red:new:6 name = input('Car name: ') for line in fil
def rental():
with open('cars.txt', 'r') as file: # cars.txt example:
# bmw:320:red:new:6
name = input('Car name: ')
for line in file:
s = line.split(':')`enter code here`
if name == s[0] :
amount = eval(input('Amount of cars'))
if amount > int(s[4]):
print('Amount is too big')
else:
t = str(int(s[4])-int(kolicina))
line.replace(s[4], t)
else:
print('Car does not exist')
如果使用“r”调用open,它将处于只读模式,因此如果希望能够写入文件,请使用“r+”,例如:
open('cars.txt',r+)
。
另外,line.replace
将返回字符串的副本,而不会替换文件中的行。
要替换它,最简单的方法就是读入所有内容,更改要更改的行,然后再将其写出来。否则,您也可以使用模块再次直接跳转到右侧行。
如果可能的话,我建议在程序开始时读取文件,并在程序运行时将所有信息保存在RAM中,只在最后写入文件(或者在明确要求时写入),因为文件访问速度很慢。您应该查看可能重复的OT,但这段代码需要重构:在处理文件之前,应该询问并验证用户输入