Python Forum
I am writing a car rental program on python. In this function I am trying to modify
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I am writing a car rental program on python. In this function I am trying to modify
#1
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()
buran write Aug-05-2021, 03:31 PM:
Please, use proper tags when post code, traceback, output, etc. This time I have added tags for you.
See BBcode help for more info.

Please, post the entire traceback that you get. We need to see the whole thing. Do not just give us the last line.
Take a time to read What to include in a post
Reply
#2
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!
aboo likes this post
while dad_has_cigs == True:
    happiness = True
    if dad_has_cigs == False:
    print("Dad come home!")
    happiness = not happiness
    break
Reply
#3
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 acc  
I 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 argument
I 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.close
And 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')
aboo likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Function parameter not writing to variable Karp 5 891 Aug-07-2023, 05:58 PM
Last Post: Karp
Question Help me modify this .txt into .csv with Python mgzz 1 721 Dec-14-2022, 01:38 PM
Last Post: Axel_Erfurt
  Create a function for writing to SQL data to csv mg24 4 1,111 Oct-01-2022, 04:30 AM
Last Post: mg24
  Noob here. Random quiz program. Using a while loop function and alot of conditionals. monkeydesu 6 1,318 Sep-07-2022, 02:01 AM
Last Post: kaega2
  How to modify python script to append data on file using sql server 2019? ahmedbarbary 1 1,175 Aug-03-2022, 06:03 AM
Last Post: Pedroski55
  Writing into 2 text files from the same function paul18fr 4 1,628 Jul-28-2022, 04:34 AM
Last Post: ndc85430
  Writing on an lcd display gives problems to the program Idontknowany 1 1,377 Nov-15-2021, 10:46 PM
Last Post: Larz60+
  Writing a lambda function that sorts dictionary GJG 1 1,985 Mar-09-2021, 06:44 PM
Last Post: buran
  Writing a function to calculate time range in Unix Epoch Time t4keheart 2 2,930 Jul-15-2020, 01:55 AM
Last Post: t4keheart
  Modify code from running program ? samuelbachorik 2 2,406 Jun-26-2020, 08:17 PM
Last Post: samuelbachorik

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020