-2

so im stuck with this code, point of it is that you enter car name and amount of car that you want to rent but i can figure out how to change string in .txt file after you rent cars

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') 
louseDepo
  • 11
  • 3

1 Answers1

0

If you call open with 'r', it will be in read-only mode, so use 'r+' if you want to be able to write to the file, like so: open('cars.txt', 'r+'). Also, line.replace will return a copy of the string, and not replace the line in your file. To replace it, the easiest is just to read everything in, change the line you want changed, and then write it out again. Otherwise you can also use the linecache module to jump directly to the right line again. If at all possible, I suggest reading in the file at the start of the program and keeping all the info in RAM while the program is running, only writing it to file at the very end (or when explicitly asked to do so), since file access is slow.

melk
  • 530
  • 3
  • 9