嗨我想從命令行使用argparse輸入文件名,但我努力讓它工作。使用argparse來輸入文件名
我想從命令行(-d)傳遞一個對應於文件名(datbase.csv)的字符串,並將其存儲在變量inputargs.snp_database_location中。
這將作爲我的load_search_snaps函數的輸入,如下面的代碼所示,它打開文件並對它執行一些操作(僞代碼)。
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)
使用在bash命令:
python3 snp_freq_V1-0_export.py -d snpstocheck.csv
我收到以下錯誤,當我嘗試從同一目錄傳遞一個普通的CSV文件中使用的命令行:
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']
如果我從腳本內部提供文件路徑,它可以很好地工作。據我可以告訴我得到一個匹配文件名字符串的snp_database_location的字符串,但後來我得到了錯誤。我錯過了什麼是給類型錯誤?
您在錯誤消息中缺少'[]'。列表和字符串之間的區別很重要。 – hpaulj