Define a class containing methods for reading a file and then storelines in external variable

J

Joug Raw

Hi,

I am really new in python programming and I want to build a class that perform various functions to the content(or lines) of any given file. I want to first include the opening and reading file function into that class, then add other methods.

Here is what I wrote for opening file and reading the lines:

class FileOpration:
def __init__(self,name):
self.name = name
self.filename = self.name
def readAllline(self):
open(self.name).readlines()

file1 = FileOpration("myfile.txt")
print file1.filename
allines = file1.readAllline()
print allines

I define self.name variable because I want to store the specific file that I read. This works fine by the test code of print file1.filename. I saw "myfile.txt" on the terminal output.

However, the readAllline() method dose not work. The code only give me "None" as the output on terminal

What was wrong with this code? Thank for the help.
 
C

Chris Angelico

class FileOpration:
def __init__(self,name):
self.name = name
self.filename = self.name
def readAllline(self):
open(self.name).readlines()

file1 = FileOpration("myfile.txt")
print file1.filename
allines = file1.readAllline()

You probably want to return that value:
def readAllline(self):
return open(self.name).readlines()

Then it'll do what you expect. But why wrap this up in a class? Why
not simply call the underlying functions directly?

ChrisA
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top