Поиск, сколько строк находится в файле TXT, используя пользовательский класс в PythonPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Поиск, сколько строк находится в файле TXT, используя пользовательский класс в Python

Сообщение Anonymous »

Я пытаюсь создать класс в Python под названием EasyFile , который позволил бы мне читать и записать в файл из любого места, которое я назвал Cursor в программе. Один тест, который я сделал, включает в себя перемещение курсора вниз по линии из файла TXT в цикле, пока я не получу эофиррор . Я удалил ненужные методы и обработку исключений, чтобы создать минимальный воспроизводимый пример: < /p>

Код: Выделить всё

def main():
file = EasyFile("numbers.txt")
file.write("1, -2, 5, 0, 19, -7, end\n5, 5, -1, -10, 9, end")
lineCount = 0
while(True):
try:
print("Line #"+str(lineCount+1))
file.moveCursorToLine(lineCount)
except EOFError:
break
lineCount += 1
print("The amount of lines are: "+str(lineCount + 1))

class EasyFile():

#Members:
#filename
#writer
#reader
#cursor

def __init__(this,filename):
this.filename = filename
this.cursor = 0
this.writer = open(filename,"w") #open one instance for writing
this.reader = open(filename,"r") #open another instance for reading
this.writer.seek(this.cursor)
this.reader.seek(this.cursor) #set the cursor to the beginning

def moveCursor(this, charNum): #charNum = 0 will reset file cursor. charNum is kinda like the incidices of an array where they start at 0
this.cursor = charNum
this.writer.seek(charNum)
this.reader.seek(charNum)
temp = open(this.filename,"r") #temp is created to check EOF without using this.reader so reader.tell() is in sync with this.cursor
temp.seek(charNum)
if(temp.read(1)==""): #if there is nothing after the file...
temp.seek(charNum-1) #check the previous character
if(temp.read(1)==""): #if there is still nothing...
temp.close()
raise EOFError #we were at the end of the file
temp.close()

def moveCursorToLine(this, lineNum): #lineNum = 0 will reset file cursor. lineNum is kinda like the indices of an array where it starts at 0
this.moveCursor(0)
for i in range(0,lineNum):
print(repr(this.readUntil()))

def write(this,string):
this.writer.write(string)
this.writer.flush() #make sure the file is updated for future use
this.moveCursor(this.cursor+len(string)) #move the cursor to the end of what was just written

def readUntil(this,buffer="\n"):
string = this.reader.read() #gather a string of everything past the cursor
this.moveCursor(this.cursor) #re-sync this.reader.tell() and this.cursor
endChar = 0
while(len(string)>endChar):
if(string[endChar:endChar+len(buffer)]==buffer): #check if a selected portion of the read file is equal to the buffer
break
if(len(string[endChar:endChar+len(buffer)])!=len(buffer)): #check if the previously selected portion is the same length as the buffer. If it's not that means we're at the end of the file
this.moveCursor(this.cursor+len(string)) #move the cursor to the end of the file
return string #return the enitre read content if there was no buffer present in the read content
endChar += 1 #add one character to the future return value
this.moveCursor(this.cursor+endChar+len(buffer)) #The cursor is currently on the buffer, so +len(buffer) would move it past the line
return string[0:endChar] #take a substring

main()

< /code>
Вывод, который я надеялся получить из этого теста, будет: < /p>
Line #1
'1, -2, 5, 0, 19, -7, end'
Line #2
'5, 5, -1, -10, 9, end'
The amount of lines are: 2
< /code>
Однако я вместо этого получаю выход: < /p>
Line #1
Line #2
'1, -2, 5, 0, 19, -7, end'
Line #3
'1, -2, 5, 0, 19, -7, end'
''
Line #4
'1, -2, 5, 0, 19, -7, end'
''
The amount of lines are: 4
< /code>
Я относительно новичок в кодировании Python и немного застрял после работы над этим в течение последних двух дней. Я думаю, что проблема в Def Readuntil (this, buffer = "\ n") 
, как я думаю, логика в MoveCursor и MoveCursortoline звучит. Я надеюсь избежать импортной ОС , чтобы я мог просто применить ванильные инструменты для FileHandling. Заранее спасибо


Подробнее здесь: https://stackoverflow.com/questions/796 ... -in-python
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»