How to open file using argparse?

后端 未结 5 1652
南方客
南方客 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: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

提交回复
热议问题