Multiple files for one argument in argparse Python 2.7

后端 未结 2 1948
灰色年华
灰色年华 2020-12-25 12:05

Trying to make an argument in argparse where one can input several file names that can be read. In this example, i\'m just trying to print each of the file

相关标签:
2条回答
  • 2020-12-25 13:00

    Just had to make sure there was at least one argument

    parser.add_argument('file',nargs='*')
    
    0 讨论(0)
  • 2020-12-25 13:02

    If your goal is to read one or more readable files, you can try this:

    parser.add_argument('file', type=argparse.FileType('r'), nargs='+')
    

    nargs='+' gathers all command line arguments into a list. There must also be one or more arguments or an error message will be generated.

    type=argparse.FileType('r') tries to open each argument as a file for reading. It will generate an error message if argparse cannot open the file. You can use this for checking whether the argument is a valid and readable file.

    Alternatively, if your goal is to read zero or more readable files, you can simply replace nargs='+' with nargs='*'. This will give you an empty list if no command line arguments are supplied. Maybe you might want to open stdin if you're not given any files - if so just add default=[sys.stdin] as a parameter to add_argument.

    And then to process the files in the list:

    args = parser.parse_args()
    for f in args.file:
        for line in f:
            # process file...
    

    More about nargs: https://docs.python.org/2/library/argparse.html#nargs

    More about type: https://docs.python.org/2/library/argparse.html#type

    0 讨论(0)
提交回复
热议问题