Reputation: 175
I am trying to supply csv file as an argument in python file, Here, I want to pass features.csv file as an argument. Any thoughts how to make it?
def read_csv_file():
with open(r'features.csv', 'r') as csvFile:
checker = lambda i: bool(i and i.strip())
raw_file = csv.reader(csvFile)
header = next(raw_file)
folders = next(
{
header[0]: [row[0]],
'Feature Name': list(filter(checker, row[:1])),
'Child folder': list(filter(checker, row[1:]))
} for row in raw_file
)
raw_folder_list = list(folders.values())
folder_list = sum(raw_folder_list, [])
return folder_list
Upvotes: 3
Views: 9057
Reputation: 180
I think you are trying to make filename a command line argument so that, you can reuse this code to open all similar csv files.
In that case, you can use argparse
or, simply
>> python read_csv.py filename.csv
In read_csv.py
import sys
first_arg = sys.argv[1]
print(first_arg)
# filename.csv
I would recommend using argparse since it is more robust.
Upvotes: 2
Reputation: 679
def read_csv_file(file_name):
with open(file_name, 'r') as csvFile:
checker = lambda i: bool(i and i.strip())
raw_file = csv.reader(csvFile)
header = next(raw_file)
folders = next(
{
header[0]: [row[0]],
'Feature Name': list(filter(checker, row[:1])),
'Child folder': list(filter(checker, row[1:]))
} for row in raw_file
)
raw_folder_list = list(folders.values())
folder_list = sum(raw_folder_list, [])
return folder_list
call function with file name like: read_csv_file('features.csv')
Upvotes: 1