0

I am following this advice: File as command line argument for argparse - error message if argument is not valid to print the contents of a file. Here is an MWE:

import argparse
import os


def is_valid_file(parser, arg):
    """

    :rtype : open file handle
    """
    if not os.path.exists(arg):
        parser.error("The file %s does not exist!" % arg)
    else:
        return open(arg, 'r')  # return an open file handle


parser = argparse.ArgumentParser(description='do shit')
parser.add_argument("-i", dest="filename", required=True,
                    help="input file with two matrices", metavar="FILE",
                    type=lambda x: is_valid_file(parser, x))

args = parser.parse_args()

print(args.filename.read)

However, I am getting this instead of the file content:

<built-in method read of _io.TextIOWrapper object at 0x7f1988b3bb40>

What am I doing wrong?

1 Answer 1

4

replace this :

print(args.filename.read)

to:

print(args.filename.read())

Read about Class and object here: Class and Object

1
  • @Zubo That is due to how python functions are first class objects. By typing filename.read you are getting an object. The () characters "call" the object. Note: f = foo(); f.a = 4; f.a(); TypeError: 'int' object is not callable Dec 15, 2014 at 22:43

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.