Using argparse to for filename input
argparse, bash, python, python-3.x
Solution
`nargs=1` makes `inputargs.snp_database_location` a list (with one element), not a string.
In [49]: import argparse
In [50]: parser = argparse.ArgumentParser()
In [51]: parser.add_argument('-d', nargs=1)
Out[51]: _StoreAction(option_strings=['-d'], dest='d', nargs=1, const=None, default=None, type=None, choices=None, help=None, metavar=None)
In [52]: args = parser.parse_args(['-d', 'snpstocheck.csv'])
In [53]: args.d
Out[53]: ['snpstocheck.csv']
To fix, remove `nargs=1`.
Problem
Hi I'm trying to use argparse for filename input from command line but I'm struggling to get it working. I want to take a string passed from the command line (-d) which corresponds to a filename (datbase.csv) and store it in the variable inputargs.snp_database_location. This gets taken as input to my load_search_snaps function as shown in my code below which opens the file and does stuff (pseudocode) to it. ``` import csv, sys, argparse parser = argparse.ArgumentParser(description='Search a list of variants against the in house database') parser.add_argument('-d', '--database', action='store', dest='snp_database_location', type=str, nargs=1, help='File location for the in house variant database', default='Error: Database location must be specified') inputargs = parser.parse_args() def load_search_snps(input_file): with open(input_file, 'r+') as varin: id_store_dictgroup = csv.DictReader(varin) #do things with id_store_dictgroup return result load_search_snps(inputargs.snp_database_location) ``` using the command in bash: python3 snp_freq_V1-0_export.py -d snpstocheck.csv I get the following error when I try and pass it a regular csv file from the same directory using command line: File "snp_freq_V1-0_export.py", line 33, in load_search_snps with open(input_file, 'r+') as varin: TypeError: invalid file: ['snpstocheck.csv'] If I feed the filepath in from within the script it works perfectly. As far as I can tell I get a string for snp_database_location which matches the filename string, but then I get the error. What am I missing that's giving the type error?