Reputation: 39
I am writing a class in python to revise a line in a text file. The code is tested to be functioning well when running alone.
class fileeditor:
def __init__ (self,a,b):
self.a = a
self.b = b
self.c = 0
print 0
def editinputfile (self):
return 0
with open (self.a,"r") as my_file:
for line in my_file:
if line.strip():
self.c+=1
self.c=self.c-2
with open (self.a,"r") as my_file:
lines=my_file.readlines()
lines[self.c]= self.b
with open (self.a,"w") as my_file:
my_file.write(''.join(lines))
my_file.close()
But when i tried to call it from another file, it doesn't work. self.a
is the address of the text file while self.b
is the string that will overwrite one line in the text file.
from editor import fileeditor
a=".\test.txt"
b='1 2 4 5\n'
fileeditor(a, b)
Upvotes: 1
Views: 1285
Reputation: 361
First you should remove return 0
in editinputfile
. Then you should also call this function.
from editor import fileeditor
a=".\test.txt"
b='1 2 4 5\n'
myfe = fileeditor(a, b)
myfe.editinputfile()
Upvotes: 1
Reputation: 58885
By the example you gave it seems that you are only creating the new instance but not calling the editinputfile
method. Try to do:
fe = fileeditor(a, b)
fe.editinputfile()
Upvotes: 4