1

I have spent the past two days on this and I've drawn blank, hopefully someone can help.

I have 3 values assigned to variables that are always going to be the same. I then have a fourth value assigned to a variable that is going to be different each time on user input. The intention is to take user input for all 4 values. On the fourth value I want the program to ask me for input repeatedly until I press "q" for example. Each time I enter a value it appends to a CSV file with the existing 3 values already entered. After q, continue with the script.

value1 = input("enter value1 ")
value2 = input("enter value2 ")
value3 = input("enter value3 ")
value4 = input("enter value4 ")
value4 = input("enter value4 ")
...
...
...
q

CSV file should be like this, ensuring that the first three values are constant but the fourth value is different per each entry.

column1,column2,column3,column4
value1,value2,value3,something_new
value1,value2,value3,something_new2
value1,value2,value3,something_new3
value1,value2,value3,something_new4
value1,value2,value3,something_new5
value1,value2,value3,something_new6
...
...
...

I had the below code that takes the values and adds 1 row in a CSV file each time. I've tried using file mode 'a' but I can't seem to add a new row in the CSV for the next. And when I add a for loop to the code below I get the "TypeError: 'DictWriter' object is not iterable" error.

with open('file_append.csv', 'w', newline='') as file:
    fieldnames = ['column1', 'column2', 'column3', 'column4']
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({'column1': value1, 'column2': value2, 'column3': value3, 'column4': value4})

I'm getting lost on adding for/while loops, if statements, if anyone can't point me in the right direction or show me a working solution it would be much appreciated

I have looked at many stack overflows and blogs but nothing is helping me solve this.

how to append to a new row when writing to CSV file

How to append new data onto a new line

Appending data to csv file

wakey
  • 2,283
  • 4
  • 31
  • 58
Aaron
  • 65
  • 5
  • Can you perhaps provide a complete example where you are hitting this issue? Your code above (writing to `file_append.csv`) looks like it would run without any issues. I'm unsure how you're using writer to end up getting the `object is not iterable` error. – wakey Nov 17 '20 at 12:43
  • Your code example is incomplete - the input part is missing. Id' rather go and collect the user's input in a loop and then write to the file. For that, you only have to loop the `writerow` part – tuergeist Nov 17 '20 at 12:44

2 Answers2

-1
import csv
value1 = input("enter value1 ")
value2 = input("enter value2 ")
value3 = input("enter value3 ")
value4 = '0'

data = []

while True:
    value4 = input("enter value4 ")
    if value4.upper() == "Q":
        break
    data.append([value1,value2,value3,value4])
    

with open('file_append.csv', 'w', newline='') as file:
    writer = csv.writer(file, delimiter=',')
    fieldnames = ['column1', 'column2', 'column3', 'column4']
    writer.writerow(['column1', 'column2', 'column3', 'column4'])
    for row in data:
        writer.writerow(row)

import pandas as pd
pd.read_csv('file_append.csv')
Equinox
  • 6,483
  • 3
  • 23
  • 32
-1

You could try something like this. This snippet uses the so-called "walrus operator" (:=), which is only available in Python 3.8. It also uses f-strings, which are available since Python 3.6. Neither of these features are strictly required, and it's trivial to rewrite the code without these features if necessary. The itertools import is also not required, it's just a cute way of counting starting at 1, going upwards. Naturally, you can use a DictWriter, if you like.

def main():

    import csv
    import itertools

    fieldnames = ["fruit", "beverage", "desert", "name"]

    with open("output.csv", "w", newline="") as file:

        constant_values = [input(f"What {fieldname} does the diet consist of?: ") for fieldname in fieldnames[:-1]]
        
        writer = csv.writer(file)
        writer.writerow(fieldnames)
        
        count = itertools.count(1)
        while (name := input(f"What is the name of person# {next(count)}?: ")) != "q":
            writer.writerow(constant_values + [name])
        print("Done!")

    return 0


if __name__ == "__main__":
    import sys
    sys.exit(main())

Output:

What fruit does the diet consist of?: Apple
What beverage does the diet consist of?: Coke
What desert does the diet consist of?: Ice Cream
What is the name of person# 1?: John
What is the name of person# 2?: Jerry
What is the name of person# 3?: George
What is the name of person# 4?: Harry
What is the name of person# 5?: Sam
What is the name of person# 6?: q
Done!
>>> 

CSV file:

fruit,beverage,desert,name
Apple,Coke,Ice Cream,John
Apple,Coke,Ice Cream,Jerry
Apple,Coke,Ice Cream,George
Apple,Coke,Ice Cream,Harry
Apple,Coke,Ice Cream,Sam
Paul M.
  • 10,481
  • 2
  • 9
  • 15