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: