Файлы являются итераторами в Python, поэтому вы можете прочитать дескриптор файла только один раз.Вы пытаетесь прочитать один и тот же дескриптор здесь три раза, поэтому последние два ничего не делают:
class TextReader:
def __init__(self, spec):
self.file = open(spec, 'r+')
self.text = self.file.read() # < reads the iterator -- it is now spent
self.lines = 0
for _ in self.file: # < try to read again does nothing
self.lines += 1 # < this never runs
def replace(self, old, new):
replace = ''
for line in self.file: # < try to read again; loop again doesn't run
replace += line.replace(old, new) + '\n'
self.file.write(replace)
Если вы хотите считать строки, а затем читать эти строки одну за другой, просто прочитайте файл в список,Тогда count
будет длина списка.Что-то вроде:
class TextReader:
def __init__(self, spec):
self.file = open(spec, 'r+')
# alternative to below:
# self.lines = list(self.file)
self.lines = []
for line in self.file:
self.lines.append(line)
def replace(self, old, new):
replace = ''
for line in self.lines:
replace += line.replace(old, new) + '\n'
self.file.write(replace)
self.file.close() # remember to close the file!
t = TextReader('test.txt')
t.replace('good', 'bad')
print(t.lines)
print(len(t.lines))
Это приведет к созданию файла с двумя строками - исходной строкой и добавленной строкой с good
, замененными на bad
.Это потому, что вы открываете с r+
, что означает добавление.