How to open file using argparse?

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

提交回复
热议问题