Appending and retrieving from CSV

31 Views Asked by At

I’m currently working on a Python project in Thonny and need to implement CSV as a ‘database requirement’

When the program is run, the user makes three inputs. These inputs are appended to their individual list, e.g input 1 appended to list 1 and so on.

Essentially, I want to save these three inputs in one CSV row

When the program is run again, I want the list to be retrieved- then inputs again, and append.

Basically this is a way of saving the inputs, however i need to retrieve them when the code is run again because that data is manipulated later on.

I haven’t dealt much with CSV, and I’m not sure whether i need two separate function to read and write, and where to position them in the code sequence so that i get the desired result.

1

There are 1 best solutions below

1
S_Anuj On

I'm not sure, is this going to work?

import csv

# Function to write data to the CSV file
def write_to_csv(data):
    with open('data.csv', 'a', newline='') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(data)

# Function to read data from the CSV file
def read_from_csv():
    try:
        with open('data.csv', 'r') as csvfile:
            reader = csv.reader(csvfile)
            data = list(reader)
        return data
    except FileNotFoundError:
        return []

# Main program
def main():
    # Read existing data from CSV file
    existing_data = read_from_csv()
    
    # Get user inputs
    input1 = input("Enter input 1: ")
    input2 = input("Enter input 2: ")
    input3 = input("Enter input 3: ")
    
    # Append inputs to a new row
    new_row = [input1, input2, input3]
    existing_data.append(new_row)
    
    # Write updated data to CSV file
    write_to_csv(new_row)
    
    # Manipulate the data as needed in your program
    print("Data saved and manipulated successfully.")

if __name__ == "__main__":
    main()