2

I am quite new to coding and so I don't know how to set input from the program user to a csv file on different lines. All it does at the moment is print it all on one line, which isn't useful. Any help would be appreciated. Also, sorry for bad code quality - I'm learning as fast as I can!

Here's the code:

import csv

def filecreator():
    print("----------INPUT--DATA----------")
    filename = input("File Name: ")
    print("A file has been created named",filename,".csv")
    print("-------------------------------")

    with open(filename+".csv", 'w', newline='') as csvfile:
        w = csv.writer(csvfile, delimiter=',')
        save = "y"
        while save == "y":
            device = input("Source of data: ")
            time_of_data_collection = ("When: ")
            first_data_set = input("Column 3 Title: ")
            second_data_set = input("Column 4 Title: ")
            #Here is where I want to have the break for it to be printed on a
            #second line
            drone = int(input("Drone Number: "))
            time = int(input("Time: "))
            temperature = input("Enter temperature: ")  
            windspeed = input("Enter windspeed: ")
            
            save = input("Would you like to save? Y/N: ")  
            if save.lower() == "y":
                w.writerow([drone, time, temperature, windspeed])   
                print("---Your data has been saved---")

        print("Program closed.")

def viewdata():
    print("----VIEW-DATA----")
    filename = input("File Name: ")
    print("-----------------")
    f = open(filename)
    csv_f = csv.reader(f)

    for row in csv_f:
      print (row)

    print("-----------------")

userinput = input("Enter I to input data, V to view data or C to do calculations: ")

if userinput in ("I", "i"):
    print("\nYou have chosen to input weather data to the program")
    filecreator()

elif userinput=="V" or "v":
    print("\nYou have chosen to view weather data.")
    viewdata()

elif userinput=="C" or "c":
    print("\nYou have chosen to perform calculations with weather data.")
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Jonesy19
  • 63
  • 1
  • 5

3 Answers3

1

To set a header-column above the aquired data, ask for them before the loop asking for data and write them once the same way you do for your data entries using w.writerow([drone_header, time_header, temperature_header, windspeed_header]) containing the column header information instead.

Each call to csv_writer.writerow( [...] ) will write one line. You can write all data at once if you use csv_writer.writerows( [ [...], [...], [...], ... ) and provide a list of lists - each inner list represents one row of data.

Read more here:


You still have plenty of other things that need fixing:

  • elif userinput=="V" or "v": and elif userinput=="C" or "c":
  • inputting time as an integer?
  • no user input sanitation (for empty inputs, invalid numbers etc)
  • current code is a mix of input, output, writing to file etc. - generally you want to structure it a bit better so you have sections like: Input, Processing then output (you can mix and match but it makes it harder.

You could fix them like so:

import csv

def get_int(text, positive_only = True):
    """Handles input for valid (maybe positive only) integers"""
    while True:
        try:
            i = input(text)
            v = int(i)
            if positive_only and v < 0:
                raise ValueError()
            return v
        except ValueError:
            print(f"You need to input a {'non negative ' if positive_only else ''}number")

def filecreator():
    print("----------INPUT--DATA----------")
    filename = input("File Name: ") 

    # fix the filename for good and force a .csv extension
    if not filename.endswith(".csv"):
        filename += ".csv"
    print("Will use ",filename, "to store data.")
    print("-------------------------------")

    # ask headers (INPUT)
    headers = []
    while not headers:
        try:
            headerinput = input("Please enter column headers.They are used as heade for:\n\tdevice, time, data1 (Temperature), data2 (Windspeed)\nInput all comma seperated in one line (): ")
            device_header,time_header, data1_header, data2_header  = [h.strip() for h in headerinput.split(",") if h.strip()]
        except (ValueError, IndexError):
            continue
        headers = [device_header,time_header, data1_header, data2_header]

    # store all datapoinst in a list and write only once afterwards
    data = []
    while True:
        print("Data input:")
        drone = get_int(f"Drone Number ({device_header}):")
        time = get_int(f"Time ({time_header}):") # time as integer? 
        temperature = input(f"Enter temperature ({data1_header}):")
        windspeed = input(f"Enter windspeed ({data2_header}): ")

        data.append([drone,time,temperature,windspeed])

        save = input("Continue data entry? [Y/N]").lower().strip()
        if save == "n":
            break

    # not much of (PROCESSING) done with the data so ... empty 

    # write file (OUTPUT)
    with open(filename, "w", newline ="") as csvfile:
        w = csv.writer(csvfile, delimiter=',')
        w.writerow(headers)
        w.writerows(data)
        print("---Your data has been saved---")
    print("Program closed.")

def viewdata():
    print("----VIEW-DATA----")
    filename = input("File Name: ")
    print("-----------------")
    with open(filename) as f:
        csv_f = csv.reader(f)
        for row in csv_f:
          print (row) 
    print("-----------------")

userinput = input("Enter I to input data, V to view data or C to do calculations: ").strip().lower()

if userinput == "i": 
    print("\nYou have chosen to input weather data to the program")
    filecreator()

elif userinput=="v":
    print("\nYou have chosen to view weather data.")
    viewdata()

elif userinput=="c":
    print("\nYou have chosen to perform calculations with weather data.")
else:
    print ("\nWrong input.")

Screen output:

Enter I to input data, V to view data or C to do calculations: i

You have chosen to input weather data to the program
----------INPUT--DATA----------
File Name: aa
Will use  aa.csv to store data.
-------------------------------
Please enter column headers.They are used as heade for:
        device, time, data1 (Temperature), data2 (Windspeed)
Input all comma seperated in one line (): drone,time,data1,data2
Data input:
Drone Number (drone):42
Time (time):0815
Enter temperature (data1):hot
Enter windspeed (data2): breeze
Continue data entry? [Y/N]y
Data input:
Drone Number (drone):11
Time (time):9999
Enter temperature (data1):boiling
Enter windspeed (data2): hurricane
Continue data entry? [Y/N]n
---Your data has been saved---
Program closed.

File created:

drone,time,data1,data2
42,815,hot,breeze
11,9999,boiling,hurricane

Other things to read and heed:

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

You just need to change this line:

with open(filename+".csv", 'w', newline='') as csvfile:

"w" is for writing a new file, which will overwrite any previous file.

Change it to "a+" instead, which will append to the file instead of overwriting it.

with open(filename+".csv", 'a+', newline='') as csvfile:

There are several arguments for the open() method, it might be useful to look at them and learn how they work.

0

I do not have your data file to test, but if you want to go to next line on the screen, just add where it is needed:

print("\n")

Ortherwise the writerow method should write one a new line each time. If you want to go to next line, juste write "\n" in the file where needed.

You can add the "\n", when writing your data:

w.writerow([drone, time, "\n", temperature, windspeed])

But be carefull when you need to read the file. Hope this helps. Otherwise juste give us more details and sample input and output data please.

Malo
  • 1,233
  • 1
  • 8
  • 25
  • I don't think this is what the author meant. The code asks the user for a series of inputs and saves the answers on disk. But the way it is written, it overwrites if the user inputs the same csv file. This is because they are opening the file with "w" instead of "a" – Marcos Vinícius Petri Nov 22 '20 at 10:44
  • 1
    The OP may have two issues : writing several data samples. He can loop or append like you propose. But the method is called "filecreator". There is a comment "#Here is where I want to have the break for it to be printed on a #second line" so maybee he just wants to add a newline after the column header. Not very clear tough. – Malo Nov 22 '20 at 10:46