Reputation: 13
I'm a little bit new to python and programming in general so I'm not sure if I'm using the terminology correctly but,
I have a short program that I am writing that will read the words in a text file, split them into an array and then output only words with a specified length.
However, I have run into an issue when trying to set up the array and file variables. While overall the program works, in each function I am re-instantiating the file variable (File = open() to File.close) and I am wondering if there is any way to make the variables class-wide.
I have tried making them class-wide by indenting before the functions, but then I get an error because name
and set_length
have not been instantiated yet.
As I said, this is one of the first times I am working with classes, so any advice would be helpful. Thanks!
class FileParser:
def __init__(self,name,set_length):
self.name = name
self.set_length = set_length
def Print_words(self):
File = open(self.name, "r")
Allwords = File.read()
words = Allwords.split("\n")
File.close()
for word in words:
if len(word) <= self.set_length:
print(word)
def length_counter(self):
File = open(self.name, "r")
Allwords = File.read()
words = Allwords.split("\n")
File.close()
x = 0
for word in words:
x += 1
text = "there are {} many words in this file".format(x)
return text
Upvotes: 0
Views: 232
Reputation: 780798
It shouldn't be a class variable, since each FileParser
instance reads a different file.
You can read the file in the __init__
method and assign the list of words to an instance attribute.
class FileParser:
def __init__(self,name,set_length):
self.name = name
self.set_length = set_length
with open(name, "r") as f:
data = f.read()
self.words = data.split("\n")
def Print_words(self):
for word in self.words:
if len(word) <= self.set_length:
print(word)
def length_counter(self):
text = "there are {} many words in this file".format(len(self.words))
return text
Upvotes: 1