1
%%writefile testcipher.py
import argparse
def parse_command_line():
    parser=argparse.ArgumentParser()
    parser.add_argument("infile",type=argparse.FileType('r'),help="show this help message and exit")
    args=parser.parse_args()

def read_file(file_path):
    with open(file_path,"r") as f:
        message=f.read()
    return message
args = parse_command_line()
read_file(args.infile)

----------

%%bash

python3 testcipher.py plain_message.txt


----------

Traceback (most recent call last):
  File "testcipher.py", line 13, in <module>
    read_file(args.infile)
AttributeError: 'NoneType' object has no attribute 'infile'

I tried to read file with parser argument, somehow it didnt work..help please..

ignore for word requirement ignore for word requirement ignore for word requirement

2 Answers 2

1

(1) You need return 'args' in your parse_command_line() function.

(2) Your add_argment function lead to open file directly using your argument as file name.

%%writefile testcipher.py

import argparse
def parse_command_line():
    parser=argparse.ArgumentParser()
    parser.add_argument("infile",type=str,help="show this help message and exit")
    args=parser.parse_args()
    return args

def read_file(file_name):
    __file = open(file_name)
    message=__file.read()
    return message

args = parse_command_line()
message = read_file(args.infile)
print (message)

----------

%%bash

python3 testcipher.py plain_message.txt


----------
Sign up to request clarification or add additional context in comments.

1 Comment

I tried your code, it returns:TypeError: invalid file: <_io.TextIOWrapper name='plain_message.txt' mode='r' encoding='UTF-8'>
0

parse_command_line must return args object. Actually your parsing function returns None.

And of course None hasn’t any attribute whatever it’s name.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.