How to open file using argparse?

后端 未结 5 1629
南方客
南方客 2020-11-29 19:13

I want to open file for reading using argparse. In cmd it must look like: my_program.py /filepath

That\'s my try:

parser = argparse.ArgumentParser()
         


        
相关标签:
5条回答
  • 2020-11-29 19:19

    Take a look at the documentation: https://docs.python.org/3/library/argparse.html#type

    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument('file', type=argparse.FileType('r'))
    args = parser.parse_args()
    
    print(args.file.readlines())
    
    0 讨论(0)
  • 2020-11-29 19:24

    In order to have the file closed gracefully, you can combine argparse.FileType with the "with" statement

    # ....
    
    parser.add_argument('file', type=argparse.FileType('r'))
    args = parser.parse_args()
    
    with args.file as file:
        print file.read()
    

    --- update ---

    Oh, @Wernight already said that in comments

    0 讨论(0)
  • 2020-11-29 19:44

    This implementation allows the "file name" parameter to be optional, as well as giving a short description if and when the user enters the -h or --help argument.

    parser = argparse.ArgumentParser(description='Foo is a program that does things')
    parser.add_argument('filename', nargs='?')
    args = parser.parse_args()
    
    if args.filename is not None:
        print('The file name is {}'.format(args.filename))
    else:
        print('Oh well ; No args, no problems')
    
    0 讨论(0)
  • 2020-11-29 19:45

    I'll just add the option to use pathlib:

    import argparse, pathlib
    
    parser = argparse.ArgumentParser()
    parser.add_argument('file', type=pathlib.Path)
    args = parser.parse_args()
    
    with args.file.open('r') as file:
        print(file.read())
    
    0 讨论(0)
  • 2020-11-29 19:46

    The type of the argument should be string (which is default anyway). So make it like this:

    parser = argparse.ArgumentParser()
    parser.add_argument('filename')
    args = parser.parse_args()
    with open(args.filename) as file:
      # do stuff here
    
    0 讨论(0)
提交回复
热议问题