Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass CSV file as an argument to python file

Tags:

python

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
like image 373
iltech Avatar asked Nov 17 '25 03:11

iltech


1 Answers

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.

like image 195
ankesh pandey Avatar answered Nov 19 '25 17:11

ankesh pandey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!