Reputation: 23
The code I am trying to enter (python) looks like this:
class RainfallTable:
def _init_ (self, njrainfall.txt):
self.njrainfall.txt = open(njrainfall.txt, 'r')
def close(self):
if self.t:
self.t.close()
self.t = None
I am trying to get this class to simply open a file called njrainfall.txt, but I get the following error message when I do so:
File "3Homework.py", line 2
def _init_ (self, njrainfall.txt):
^
What am I doing wrong?
Upvotes: 0
Views: 3953
Reputation: 331
Remove the fullstop here
self.njrainfall.txtto something else.
Like
self.njrainfall
Upvotes: 0
Reputation: 523
It looks like you are confused with strings, parameter/variable names, and class objects.
The dot you are using in what must be a variable name (njrainfall.txt
) looks like either a string with an actual file name, or an object attribute.
As other people have pointed out already, you shall not use a dot in a variable / parameter name.
You should instead do use (I have added a try..except to handle the case in which the passed filename does not exist):
class RainfallTable:
def _init_ (self, sRainFallFilename):
try:
self.rainfallFile = open(sRainFallFilename, 'r')
except:
self.rainfallFile = None
print "file %s does not exist" % sRainFallFilename
def close(self):
if not self.rainfallFile == None :
self.rainfallFile.close()
self.rainfallFile = None
Notice I have also changed the close() method to use the same attribute as in init()
Then you can call the class like:
RainFallTable myRainFallTable( "NJ.txt" )
...
myRainFallTable.close()
Upvotes: 0
Reputation: 4441
Function/constructor should have only variables as input
You can pass text file name along with path to that init function
Better you pass text file with absolute path
class RainfallTable:
def _init_ (self, textfile):
self.t = open(textfile, 'r')
def close(self):
if self.t:
self.t.close()
self.t = None
Call it as RainfallTable('njrainfall.txt')
Upvotes: 0
Reputation: 57934
You've got a .
in your variable names, which is invalid syntax for python. Remove those in your njrainfall.txt
variables. A good substitute would be njrainfall_file
or something similar. Secondly, the init functions is written with two underscores, like so:
def __init__(self, njrainfall_file):
Here some code:
class RainfallTable:
def __init__(self, njrainfall_file):
self.njrainfall_file = open(njrainfall_file, 'r')
def close(self):
if self.t:
self.t.close()
self.t = None
Make sure to pass njrainfall_file
as a string of filename!
Upvotes: 3