Danny-san
Danny-san

Reputation: 13

Having trouble exporting user input to txt file in Python

So long story short, I have been working on a Python program and I have been trying to get what the user inputs into the program to a txt file - I received some help online overall, but a bit stumped here.. Need it to include index, make, model, color, year and mileage of the vehicles that have been input (basically what is visible in the output when user hits "4" at main menu). The idea is when user hits "6" , that list/ data will be exported to txt file named "Vehicle Inventory" and then Exit the application. The issue is definitely around end of code at elif ch == 6: ... Any assistance or resolution on this would be appreciated !! Here is what I have so far:

# automobile class
class automobile:
    # constructor
    def __init__(self, make="", model="", color="", year=2018, mileage=0):
        self.make = make
        self.model = model
        self.color = color
        self.year = year
        self.mileage = mileage

    # setter methods
    def set_make(self, make):
        self.make = make

    def set_model(self, model):
        self.model = model

    def set_color(self, color):
        self.color = color

    def set_year(self, year):
        self.year = year

    def set_mileage(self, mileage):
        self.mileage = mileage

    # getter methods
    def get_make(self):
        return self.make

    def get_model(self):
        return self.model

    def get_color(self):
        return self.color

    def get_year(self):
        return self.year

    def get_mileage(self):
        return self.mileage


# end of automobile class
# method to add a new vehicle to the inventory
def add_vehicle(v_list):
    make = input("Enter make: ")
    model = input("Enter model: ")
    color = input("Enter color: ")
    year = int(input("Enter year: "))
    mileage = int(input("Enter mileage: "))
    v = automobile(make, model, color, year, mileage)
    v_list.append(v)
    print("*** VEHICLE ADDED SUCCESSFULLY...")


# method to remove a vehicle from the inventory
def remove_vehicle(v_list):
    index = int(input("Enter the index # of vehicle you would like to remove: "))
    if index >= 0 and index < len(v_list):
        make = v_list[index].get_make()
        model = v_list[index].get_model()
        v_list.pop(index)
        print(make, model, "HAS BEEN REMOVED FROM INVENTORY !")
    else:
        print("*** INVALID INDEX #... PLEASE TRY AGAIN")


# method to update a vehicle info in the inventory
def update_vehicle(v_list):
    index = int(input("Enter the index # of vehicle you would like to update: "))
    if index >= 0 and index < len(v_list):
        make = input("Enter new make: ")
        model = input("Enter new model: ")
        color = input("Enter new color: ")
        year = int(input("Enter new year: "))
        mileage = int(input("Enter new mileage: "))
        v_list[index].set_make(make)
        v_list[index].set_model(model)
        v_list[index].set_color(color)
        v_list[index].set_year(year)
        v_list[index].set_mileage(mileage)
        print("*** UPDATED SUCCESSFULLY !")
    else:
        print("*** INVALID INDEX #... PLEASE TRY AGAIN")


# method to print all vehicle details in proper formatted order
def display_vehicles(v_list):
    print('{:10} {:10} {:10} {:10} {:10} {:10}'.format('INDEX #', 'MAKE', 'MODEL', 'COLOR', 'YEAR', 'MILEAGE'))
    for i in range(len(v_list)):
        v = v_list[i]
        print('{:10} {:10} {:10} {:10} {:10} {:10}'.format(str(i), v.get_make(), v.get_model(), v.get_color(), str(v.get_year()), str(v.get_mileage())))


v_list = []  # initial list
# looping infinitely
while True:
    # showing menu
    print("1. Add a vehicle")
    print("2. Remove a vehicle")
    print("3. Update a vehicle")
    print("4. Display all vehicle inventory")
    print("5. Exit")
    print("6. Export to 'Vehicle Inventory' txt file and Exit")
    # getting choice
    ch = int(input("*** PLEASE CHOOSE AN OPTION: "))
    # performing actions based on choice
    if ch == 1:
        add_vehicle(v_list)
    elif ch == 2:
        remove_vehicle(v_list)
    elif ch == 3:
        update_vehicle(v_list)
    elif ch == 4:
        display_vehicles(v_list)
    elif ch == 5:
        break;
    elif ch == 6:
        with open('Vehicle Inventory.txt', 'w') as filehandle:
            for display_vehicles in v_list:
                filehandle.write("%s\n" % display_vehicles)
        break;
    else:
        print("*** INVALID OPTION... PLEASE TRY AGAIN")

Upvotes: 1

Views: 120

Answers (1)

Wippo
Wippo

Reputation: 963

Executing your code, the txt file contains lines such as

<__main__.automobile object at 0x0000017F5E7017C0>.

The problem is that at line filehandle.write("%s\n" % display_vehicles) pass an object reference as data to be written to the file. As far as I know, there is no ready-made function that allows you to pass a file an object reference and have the data auto-extracted from it. If you really want to use a txt file, you can do something like this:

 with open('Vehicle Inventory.txt', 'w') as filehandle:
            for display_vehicles in v_list:
                filehandle.write("make: {}, model: {}, color: {}, year: {}, mileage:{} \n".format(display_vehicles.get_make(),display_vehicles.get_model(),display_vehicles.get_color(),display_vehicles.get_year(),display_vehicles.get_mileage()))

Output

make: car, model: a, color: red, year: 2020, mileage:20
make: car2, model: b, color: black, year: 10, mileage: 10 

A brief explanation of Format.

Format allows you to insert values into a string using a style based on placeholders. {} correspond to anonymous placeholders: this means that the value that goes in that position depends on the order used inside .format(value1, value2, ...). Alternatively, you can use named placeholders such as:

"my car is {color} and i bought it in {year}".format(color= "red", year= 2010)


About the txt file

Personally I would not use a txt file, especially since loading data from this type of file can be quite annoying in cases where you are only interested in a few rows or a certain value of each row (e.g.: all red cars). I don't know if the txt file is mandatory for you, so I won't provide any detailed info on the following alternative methods. In any case, you should know that there are other types of files that are widely used for storing information.

  • Json. The data are stored into a dictionary, i.e. a set of key-value pairs. Reading and writing files is trivial thanks to the json module
  • Csv. This is very similar to a txt but has a more structured form, as if it were a table. Each row corresponds to a record, each record consists of columns. Thanks to pandas, it is easy to use csv to extract subsets of data based on the value contained in the records or the row index. The file structure also allows you to quickly create graphs and export data to Excel.
  • Pickle. If you don't even care about human-friendly representation but just want to save the data permanently to a file, you could try pickle

Upvotes: 2

Related Questions