0

I am doing a simple project for my first python course and I am stuck in one part which I have no idea how to continue.

So in this part user should input a vehicle id that he/she wants to rent. After putting the vehicle ID, my code starts to search for that vehicle ID in the Vehicle.txt text file. If the code finds the VehicleID variable and also finds that it is "A" (which means available), it starts printing details for that specific car.

My Vehicle.txt text file looks like this;

XJY-604,Hyundai Getz,O,0,45.00,A
AJB-123,BMW mini,P,200,65.00,A
WYN-482,Ford Fiesta,O,0,40,A
BKV-943,Ford Ikon,P,150,60,A
JMB-535,Ford Flex,O,0,50,A
FKI-232,Fiat Egea,O,0,30,A
KLE-154,Toyota Corolla,O,0,40,A
ITO-444,Renault Clio,O,0,55,A
MAA-321,Honda Civic,O,0,70,A
IRK-948,Hyundai i20,O,0,30,A
TRY-475,Peugeot 2008,O,0,50,A
IBM-984,Skoda Superb,O,0,60,A
KRI-365,Opel Corsa,O,0,50,A
PMA-760,Citreon C3,O,0,55,A
NGT-407,KIA Sportage,O,0,60,A

So until this far, everything is fine; if the code finds the Vehicle ID (and the condition "A") then the code starts to print details as I want (if the condition is different or vehicle ID is not found it also prints appropriate error massages which are also perfectly working as I want).

My problem starts after this part:

After printing the details from the car, my code should change that specific car's condition from "A" (available) to "R" (rented) in the Vehicle.txt text file.

For example, let's say the user entered the Vehicle ID TRY-475 --> After this input, my excepted change in the Vehicle.txt text file is;

excepted change

But the actual change in the text file is;

actual change

My code looks like this;

from datetime import datetime
now = datetime.now()
dateandtime = now.strftime("%d/%m/%Y %H:%M:%S")

def rentVehicle():
    VehicleID = input("Please enter the vehicle ID you want to rent: ")
    with open("Vehicle.txt","r+") as f1:
        for line in f1:
            l = line.split(",")
            if l[0] == VehicleID and l[5] == "A\n" or l[5] == "A":
                renterID = input("Please enter your ID: ")
                startingodometer = input("Please enter the current odometer reading: ")
                print("\nCar",l[0],"is rented to", renterID,"\n")
                print("\t\t******************** Vehicle Details ********************\n")
                print("Vehicle ID =",l[0],"\t\tDescription =",l[1],"\t\tDaily Rate =",l[4],"\tStatus =",l[5],"\n")
                print("Renter ID =",renterID,"\tDate/time of rent =",dateandtime,"\tRent Starting Odometer =",startingodometer)
                f1.write(l[5].replace(l[5],"R\n"))
                print("\nRenting vehicle is successful!")
                break
             elif l[0] == VehicleID and l[5] == "R\n" or l[5] == "R":
                print("\nThe vehicle you entered is rented. Please display available cars from the main menu.")
                break
        else:
            print("\nThe vehicle ID you entered does not exist. Please enter a valid vehicle ID.")
            break
rentVehicle()

I think the problem is in line 17 ( f1.write(l[5].replace(l[5],"R\n"))). I searched for the other options but they also didn't give my excepted output in the Vehicle.txt text file. Additionally, I am not allowed to change my file name or add these lines to another file (manually or in the code) as it is restricted in my project work. I should only update the current Vehicle.txt via code. I would be very glad if someone solve this. For a beginner, these problems are really challenging sometimes. Thanks in advance.

ReiSsS7
  • 1
  • 2

1 Answers1

1

the problem in your code is here:

with open("Vehicle.txt","r+") as f1:
    for line in f1:
        l = line.split(",")
        if l[0] == VehicleID and l[5] == "A\n" or l[5] == "A":
            renterID = input("Please enter your ID: ")
            startingodometer = input("Please enter the current odometer reading: ")
    ~~~~~~~~~~~~~~~~~~~
            f1.write(l[5].replace(l[5],"R\n"))
    ~~~~~~~~~~~~~~~~~~~
            break
        elif l[0] == VehicleID and l[5] == "R\n" or l[5] == "R":
            print("\nThe vehicle you entered is rented. Please display available cars from the main menu.")
            break
    else:
        print("nothing found")
        break

I supposed that you are not very familiar with how does the file reading work on the background ... To put it simply, there is a buffer of a specific length (for example 1028B) whihc means it is going to read 1028B of text. The reason why it is this way is that you are unable to efficiently know, how long the line will be, and also reading from a file is slow, therefore reading as much as possible in the shortest time possible is what everyone is aiming for.

Now to your code, what happend there is that your whole file got loaded into the mentioned buffer and a file pointer ended up at the end of the file.

What you should do and is recommended to do is not to rewrite the file you are currently reading (you can check out some articles about how files actually work, sorry I am not 100% sure right now whether it even lets you to write to a file that you are reading ...).

Therefore, what you need to do, is this (this is pseudocode, in order for you to do it yourself, to gain more experience :)):

with open("Vehicle.txt","r+") as read_file:
    with open("Vehicle2.txt","w+") as write_file:
        for line in read_file:
            if (your checks):
                ... (setting up)
                write_file.write(f"{l[0]},{l[1]},{l[2]},{l[3]},{l[4]},{edited_thing}")
            else:
                write_file.write(line)

// after this, you can eighter rename these files or delete the original one and then rename the other one ther:
// vehicle.txt -> temp.txt ; Vehicle2.txt => Vehicle.txt ; delete temp.txt ?

I hope this answer helps and I wish you a nice programming journey ;)

EDIT:

I just noticed that you have multiple checks there. if you do not really need to break it, I recommend you using continue which will immediatelly start the next iteration.

StyleZ
  • 1,276
  • 3
  • 11
  • 27
  • if you got any questions, feel free to ask :) I will gladly try to answer them (if I know the answer :D) – StyleZ Nov 05 '21 at 23:19
  • 1
    Hey @StyleZ and thank you for answering me! I tried to change my code as you showed me, but I got a syntax error when I did the part write_file.write(f"{l[0]},{l[1]},{l[2]},{l[3]},{l[4]},{edited_thing}"). The syntax error is --> f-string expression part cannot include a backslash (which is a totally new syntax error to me :0). And also, my code should only update the current Vehicle.txt and not write details into another one ( I am not allowed to change file names manually or add a new file as it is restricted in my project work :/ ). I should only update the current Vehicle.txt. – ReiSsS7 Nov 06 '21 at 00:04
  • Hi, could you please provide the full error message (with the code as well). from what I understand is that you are trying to add there manually into the f-string `"\"` which is unfortunatelly not possible. what you can do, is create a variable `back_slash = "\"` and add it into the f-string `f"{x} {back_slash} {y}"`. I hope it makes sense. Also unfortunately, it is not possible to write into the file while reading and it is a bad practice to read the whole file into a varaible and rewrite it (I hope you can see why). Check out these 2 links for more information about the files: – StyleZ Nov 06 '21 at 01:22
  • https://stackoverflow.com/questions/125703/how-to-modify-a-text-file https://stackoverflow.com/questions/14271216/beginner-python-reading-and-writing-to-the-same-file/14271376 and a small advice. if you get stuck to a similar error as you have mentioned, try googling it before asking. It will make you realise, how to google efficiently :) – StyleZ Nov 06 '21 at 01:24
  • Hey again @StyleZ , after trying your steps, I corrected my errors in the previous try. It is now working as you showed, but now I can't show any appropriate messages if my conditions are different, or there is no such a VehicleID (because of that else: write_file.write(line) condition is not allowing to me add new if condition before it). Also, the code creates a new file which I manually need to rename. This will not be okay with my project work because it is restricted. I need to update the current text file via code only. And from your view, I understand that it is not possible to do :/ – ReiSsS7 Nov 06 '21 at 02:14
  • Firstly, you can add multiple condition, since in your code, you are using break in each statement. If you do not want to stop, just continue the next iteration, you keyword 'continue'. Also this should be done using a database, since you are using ID's, where inserting is possible. Lastly, i hate to say this, but if you want to risk it ... you can create a list of lines ans edit those. But it will crash on a large files / memory errors – StyleZ Nov 06 '21 at 11:53