Я пытаюсь создать класс в 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. Заранее спасибо
Я пытаюсь создать класс в Python под названием EasyFile , который позволил бы мне читать и записать в файл из любого места, которое я назвал Cursor в программе. Один тест, который я сделал, включает в себя перемещение курсора вниз по линии из файла TXT в цикле, пока я не получу эофиррор . Я удалил ненужные методы и обработку исключений, чтобы создать минимальный воспроизводимый пример: < /p> [code]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") [/code], как я думаю, логика в MoveCursor и MoveCursortoline звучит. Я надеюсь избежать импортной ОС , чтобы я мог просто применить ванильные инструменты для FileHandling. Заранее спасибо
Я пытаюсь создать класс в Python под названием EasyFile , который позволил бы мне читать и записать в файл из любого места, которое я назвал Cursor в программе. Один тест, который я сделал, включает в себя перемещение курсора вниз по линии из файла...
Я пытаюсь создать класс в Python под названием EasyFile , который позволил бы мне читать и записать в файл из любого места, которое я назвал Cursor в программе. Один тест, который я сделал, включает в себя перемещение курсора вниз по линии из файла...
У меня есть программа (ниже), которая принимает текстовые файлы и помещает их в таблицу Excel. Моя цель — извлечь данные из текстового файла, но только текст после двоеточия.
Пример txt-файла (без пробела между строками «name:» и «phone:» в txt):...
У меня есть программа (ниже), которая принимает файлы TXT и помещает их в электронную таблицу Excel. Моя цель состоит в том, чтобы извлечь данные из текстового файла, но только текст только после толстой кишки. /> Я хочу, чтобы моя программа...