I am writing a car rental program on python. In this function I am trying to modify - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: I am writing a car rental program on python. In this function I am trying to modify (/thread-34506.html) |
I am writing a car rental program on python. In this function I am trying to modify - aboo - Aug-05-2021 I am writing a car rental program on python. In this function I am trying to modify car details which are added in the details.txt file but I am getting an error "if acc[0] == var[0]:TypeError:'NoneType' object is not subscriptable" how do I fix this error ? def modifying(): global acc exist = False mod_file = open("details.txt") count = 0 for s in mod_file: var = s.split(",") # spilt the data into list var[2] = var[2].strip() if acc[0] == var[0]: exist = True break count += 1 mod_file.close() if exist != True: print("!!! Can NOT Find The Data !!!") elif exist == True: s_list = [] mod_file = open("details.txt", "r") for s in mod_file: s = s.strip() s_list.append(s) mod_file.close choice = "Y" while choice == "Y": print("\n===============================") print("---------- MODIFY Cars ----------") print("---------------------------------") print("Select the details you wish to modify") print("1. Type") print("2. Manufactured Year") print("3. details of the car") print("4. car code") print("5. Daily price rate ( USD $ )") print("6. back") while True: try: c = int(input("please select a number (1 - 5): ")) modify = ["Type", "Manufactured Year", "details of the car", "car code", "Daily price rate ( USD $ )"] if c > 0 and c < 6: new = input("\nType the New " + modify[c - 1] + ":") var[c - 1] = new temp = ",".join(var) s_list[count] = temp mod_file = open("details.txt", "w") mod_file.write("") mod_file.close() count_file = 0 for s in range(len(s_list)): mod_file = open("details.txt", "r") for counting in mod_file: count_file += 1 mod_file.close() mod_file = open("details.txt", "a") if count_file == 0: mod_file.write(s_list[s]) else: mod_file.write("\n") mod_file.write(s_list[s]) mod_file.close() print("\nDetails UPDATED") be_exit = input("\nDo you want to modify again? (Y/N): ").upper() if be_exit == "y": choice = "y" else: modifying(acc) elif c == 6: modifying(acc) else: print("\n!!! Incorrect Input !!!\n") continue except: print("\n!! NOT a Number !!!\n") continue modifying() RE: I am writing a car rental program on python. In this function I am trying to modify - jamesaarr - Aug-05-2021 Hello, Please edit your post so your code is displayed correctly. Makes it easier to read. print("Like this!")If you are pulling data from a txt file then I'd recommend using with open('text.txt') as text_file: text_data = text_file.read()That way your data is now saved to a variable, however if you would rather iterate through the lines you can do: with open('welcome.txt') as text_file; for line in text_file.readlines()It would help if you also make it print to console after each step so you can see if it's pulling the data in correctly. If you are looking to change specific items in the data it would be a lot easier using numpy. Load up your windows terminal and type in: py -m pip install numpy This will install the library so you can use it in your python program. Then try: import numpy as np def main(): array = np.genfromtxt('file.csv', delimiter='','')This will save all of the data to a 2D array which makes it easier to navigate and make changes to the file. A 2D array looks like this: array = [[1,2,3,4,5], ['a','b','c','d','e']]And you can apply conditionals as seen above: if array[0,0] ==1: #This chooses the first item in the first set eg 1 print("True") #outputs "True"You can then save the data to a new csv to test its format, and in turn overwrite each csv. You can do this with the csv module, which is used by writing "import csv" at the start of your code import csv def main(): #One block of code reading and making changes to an array def save_csv(): #declare the fields first fields = ['car model','car year'......] #have your data saved to a 2D list data = [[1,2,3,4,5],[6,7,8,9,10]] #Then write and save the file. The W here refers to write which is one of the parameters of the csv module, you also have read (r) which is the default (if another parameter isnt given it just reads it) with open("cars.csv",'w') as cars_data: write = csv.writer(cars_data) write.writerow(fields) #make note of writerow and not writerows. This means it only writes the first set unless told to do otherwise. write.writerows(data)This will write the arrays to a csv. You should also look into writing dictionaries to csv using DictWriter Hope this helps! RE: I am writing a car rental program on python. In this function I am trying to modify - deanhystad - Aug-05-2021 Your error says either acc or var is None. You could add a line to print both to see, but since the line before references var[2] it has to be acc that is None. var[2] = var[2].strip() # If no error here, var is not None. if acc[0] == var[0]:To fix the error you need to create an array and have acc reference the array before you call the modifying() function. Inside your function I see it calling itself and passing an argument. modifying(acc)Your function does not accept an argument. def modifying(): global accI think maybe what you want to do is this def modifying(acc):This would probably clear up your 'NoneType' object is not subscriptable. Of course you need to pass an array when calling the function initially. modifying() # Need to pass an array for the acc argumentI am confused about what you expect the modifying function to do. It looks like "acc" is the data for a car, and that you use the "modifying(acc)" function to modify information for that car, but you never change any of the information in acc. Why is that? You change the information in the file (in a very inefficient way), but you do not change the information in acc. If you modified the information in acc you could skip the step of reading the file to get updated information. All of this code can go away: exist = False mod_file = open("details.txt") count = 0 for s in mod_file: var = s.split(",") # spilt the data into list var[2] = var[2].strip() if acc[0] == var[0]: exist = True break count += 1 mod_file.close() if exist != True: print("!!! Can NOT Find The Data !!!") elif exist == True: s_list = [] mod_file = open("details.txt", "r") for s in mod_file: s = s.strip() s_list.append(s) mod_file.closeAnd if you change the info in acc you don't need to udpate the database until all changes have been made. def modifying(acc): choices = ["Type: ", "Manufactured Year: ", "details of the car: ", "car code: ", "Daily price rate USD $"] while True: print("\n===============================") print("---------- MODIFY Cars ----------") print("---------------------------------") print("Select the details you wish to modify") for i, choice in enumerate(choices): print(f'{i+1}. {choice}{acc[i]}') print("6. back") try: choice = int(input("please select a number (1 - 6): ")) # Convert str->int is dangerous if choice < 1 or choice > 6: raise ValueError except ValueError: choice = 0 if 0 < choice < 6: # Udate acc info acc[choice-1] = input(f'\nEnter {choices[choice-1]}') elif choice == 6: # back was selected # Update acc info in database file found = False all_cars = [] try: with open("details.txt", "r") as file: for car in file: if car.startswith(acc[0]): found = True all_cars.append(','.join(acc)) else: all_cars.append(car) if not found: all_cars.append(','.join(acc)) except FileNotFoundError: all_cars.append(','.join(acc)) with open("details.txt", "w") as file: for car in all_cars: file.write(car) break modifying(['Malibu', '2009', 'Silver', 'Sedan', '5.00'])I agree with jamesaarr that this is a horrible way to manage a database. My first suggestion would be to use an actual database instead of a text file. But this is probably some school assignment instead of a real program, and the requirement is to save the information in a file. If you have to do that, you would still get a lot of benefit from treating the file like a database. Read the file into memory at the start of the program, preferably into a dictionary so you could search for your car using a dictionary key instead of searching a bunch of strings. When you modify a car in the database you call a function to copy the modified database to the file. This way you only read the file once and write as needed. def modifying(vehicleID): choices = ["Type: ", "Manufactured Year: ", "details of the car: ", "car code: ", "Daily price rate USD $"] car = vehicles[vehicleID] while True: print("\n===============================") print("---------- MODIFY Cars ----------") print("---------------------------------") print("Select the details you wish to modify") for i, choice in enumerate(choices): print(f'{i+1}. {choice}{car[i]}') print("6. back") try: choice = int(input("please select a number (1 - 6): ")) # Convert str->int is dangerous if choice < 1 or choice > 6: raise ValueError except ValueError: choice = 0 if 0 < choice < 6: # Udate car info car[choice-1] = input(f'\nEnter {choices[choice-1]}') elsif choice == 6: # back was selected write_database() # Save changes to file read_database() # Read database file at start of program. modifying('Mailbu') |