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?

Community
  • 1
  • 1
Zubo
  • 1,543
  • 2
  • 20
  • 26

1 Answers1

4

replace this :

print(args.filename.read)

to:

print(args.filename.read())

Read about Class and object here: Class and Object

Hackaholic
  • 19,069
  • 5
  • 54
  • 72
  • @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` – Nick Humrich Dec 15 '14 at 22:43