简体   繁体   中英

how to read a txt passed by command line argument

i want to pass a txt file by command line argument using the argparse module and read the file with open() function but first thing i've encountred was this error :

AttributeError: 'dict' object has no attribute 's'

Here is my code

import argparse
parser = argparse.ArgumentParser(description="My program!", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("-s", type=argparse.FileType('r'), help="Filename/path to be passed")
args = vars(parser.parse_args())
subfile = (open(args.s, "r")).read()

you can directly read from args['s'] , since type=argparse.FileType('r') . No open() needed:

import argparse
parser = argparse.ArgumentParser(description="My program!", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("-s", type=argparse.FileType('r'), help="Filename/path to be passed")
args = vars(parser.parse_args())
data = args['s'].readlines()
print(data)

now you can call the script from the command prompt, eg as python .\\test.py -s'D:/test.txt' with test.txt containing two lines with letters 'abc':

# prints ['abc\n', 'abc\n']

edit - you can simplify the code to

parser = argparse.ArgumentParser(description="My program!", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("-f", type=argparse.FileType('r', encoding='UTF-8'), help="path/filename of file to be passed")
data = parser.parse_args().f.readlines()

changes:

  • changed the parameter name to f which I find better-suited for a filename input
  • added and encoding to type=argparse.FileType('r') - otherwise, it will take the OS default (eg on Windows: cp1252). I'd consider it better practice to explicitly specify the encoding.
  • directly accessed the io.TextIOWrapper with parser.parse_args().f instead of creating a dict object first with vars()

Replace the last line:

subfile = (open(args.s, "r")).read()

with:

with open( args['s'] ) as fin :
    subfile = fin.read()

Things magically start to work and you don't have an open file hanging around for no particular reason.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM