I keep running into the following problem where I need to declare the input_fields of an input file and I have been just copying and pasting from the file into my variable, adding a comma and quotations. For example:
input = ("First Name", "Middle Name", "Last Name")
I want to automate this process so that my programs can have a line like this:
input = inputize.function1("name_of_file.csv")
Where function1 takes the input file (“name_of_file.csv”) and returns, in this case a tuple with three strings (“First Name”, “Middle Name”, “Last Name”). As you can imagine this is a pain right now since I have to do this manually for a lot of files, many of which have very many columns…
I think I want the basic structure to look like the following, but I keep thinking there must be a very simple way to take the first line of a csv file, separate each column header, put quotes around it, and put a comma after it, then store the whole thing as a tuple…
def function1(input_file):
with open(input_file, "rb") as infile:
for line in infile:
split = line.split(",")
for item in split:
input = '"' + item + '","
return input
I hope this is helpful for other people too since it seems like a common enough/super annoying manual task, and would definitely appreciate any guidance.
ADDENDUM
I had been writing code like this:
input_fields = ("First Name", "Middle Name", "Last Name")
reader = csv.DictReader(infile, fieldnames = input_fields)
Per your answer below, it seems like the top line is moot as all I have to do is:
reader = csv.DictReader(infile)
you can use
DictReaderwhich has a fieldnames property!using built in DictReader will help you with some of the nuances involved in parsing csv files.