python:使用文件句柄打印文件内容
我谨此陈辞: 打印文件的内容。这里是一个MWE:python:使用文件句柄打印文件内容,python,argparse,filehandle,Python,Argparse,Filehandle,我谨此陈辞: 打印文件的内容。这里是一个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 ope
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)
但是,我得到的是这个而不是文件内容:
<built-in method read of _io.TextIOWrapper object at 0x7f1988b3bb40>
我做错了什么 替换这个:
print(args.filename.read)
致:
在此处阅读有关类和对象的信息:
替换此:
print(args.filename.read)
致:
在此处阅读有关类和对象的信息:
@Zubo这是因为python函数是第一类对象。通过键入filename.read,您将获得一个对象。
()
字符“调用”对象。注:f=foo();f、 a=4;f、 a();TypeError:“int”对象不可调用
@Zubo,这是由于python函数是第一类对象。通过键入filename.read,您将获得一个对象。()
字符“调用”对象。注:f=foo();f、 a=4;f、 a();TypeError:“int”对象不可调用