I have write down a simple code to open a csv file that reads data frame. The code is able to print data frame. To make this code more interactive i have integrated a functionality so that it can raise an error if sys.argv[1] is not true. Unfortunately, i am not able to properly integrate the "raise exception part", after struggling too much I'm looking for a solution. The code is given bellow (Though, i have tried so many thing with the native code but here i am pasting only the last change that i have made to achieve my goal (i.e raise exception if sys.argv[1] is not True ): Thanks
class My_csv_class(object):
def __init__(self):
self.csv_path = sys.argv[1]
def csv_open(self):
try:
self.r = pd.read_csv(self.csv_path)
except IndexError:
print "Cannot open the file: "
else:
return self.r
def print_r(self):
self.r
if __name__=="__main__":
a = My_csv_class()
a.csv_open()
a.print_r()
The exception is raised in your __init__
method. You could put the try..except
around the instance creation:
if __name__=="__main__":
try:
a = My_csv_class()
except IndexError:
print "You did not specify a file"
sys.exit(1)
a.csv_open()
a.print_r()
However, it is more common to handle command line issues outside of such code. Keep your code re-usable without a command line and put all your 'script tasks' in the __main__
guarded code:
class My_csv_class(object):
def __init__(self, filename):
self.csv_path = filename
def csv_open(self):
self.r = pd.read_csv(self.csv_path)
def print_r(self):
self.r
if __name__=="__main__":
try:
filename = sys.argv[1]
except IndexError:
print "You did not specify a file"
sys.exit(1)
a = My_csv_class(filename)
a.csv_open()
a.print_r()
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments