Tuesday, May 22, 2012

how to accept file or path as arguments to method in python

I am trying to write a method that will accept either an opened file



myFile = open("myFile.txt")
obj.writeTo(myFile)
myFile.close()


or a string with a path



obj.writeTo("myFile.txt")


The method is implemented as follows:



def writeTo(self, hessianFile):
if isinstance(hessianFile,file):
print("File type")
elif isinstance(hessianFile,str):
print("String type")
else:
pass


But this raises an error



NameError: global name 'file' is not defined


why is file type not defined? Shouldn't file be defined all the time? How should the implementation be corrected to properly handel both path an file as valid argument types





No comments:

Post a Comment