Zubo
Zubo

Reputation: 1593

python: using file handle to print contents of file

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?

Upvotes: 0

Views: 700

Answers (1)

Hackaholic
Hackaholic

Reputation: 19743

replace this :

print(args.filename.read)

to:

print(args.filename.read())

Read about Class and object here: Class and Object

Upvotes: 4

Related Questions