이것은 숙제이며 Python을 처음 접했습니다. 필자는 이중 줄 커서 기반 목록 클래스를 사용하는 텍스트 편집기 프로그램을 작성했습니다. 사용자가 편집 할 기존 파일을 열거 나 새 파일을 열어서 해당 파일에 대한 커서 기반 목록을 만들었습니다. 결국 사용자가 변경 한 내용을 파일에 저장할 수 있기를 바랍니다. 일부 오류가 발생하여 무엇을해야할지 확신이 서지 않습니다. 어떤 조언을 부탁드립니다!python 3 : 커서 기반 목록에서 파일에 쓰기
from cursor_based_list import CursorBasedList
from os.path import exists
import os
def main():
def seeFile():
"""Asks the user if they want to view their file after editing, and
if yes, prints the file without None, front, or rear."""
seeFile = input("Would you like to see your file now? Y/N: ").upper()
while not seeFile == "Y" and not seeFile == "N":
print("That is not a valid choice!")
seeFile = input("Would you like to see your file now? Y/N: ").upper()
if seeFile == "Y":
print()
print(fileList)
print()
print("---------------------------------------------------------------------")
print("Welcome to TextEd v.1, a friendly text editor program!")
print()
print("How would you like to begin?")
print()
print("O: Open an existing text file for editing")
print("N: Create a new text file for editing")
print()
response = input("Please choose an initial option: ").upper()
while response != "O" and response != "N":
print("That is not a valid initial option.")
response = input("Please choose an initial option: ").upper()
if response == "O":
fileName = input("Enter the file name: ")
while not exists(fileName):
print()
print("File " + fileName + " does not exist!")
fileName = input("Please enter a valid file name: ")
myFile = open(fileName, 'r')
data = myFile.readlines()
fileList = CursorBasedList()
for line in data:
fileList.insertAfter(line)
seeFile()
elif response == "N":
fileName = input("What would you like to name your file?: ")
fileList = CursorBasedList()
myFile = open(fileName, "w")
print()
print("TextEd Menu:")
print("---------------------------------------------------------------------")
print()
print("A: Insert a new line after the current line of your file")
print("B: Insert a new line before the current line of your file")
print("C: Display the current line of your file")
print("F: Display the first line of your file")
print("L: Display the last line of your file")
print("E: Display the next line of your file")
print("P: Display the previous line of your file")
print("D: Delete the current line of your file")
print("R: Replace the current line of your file with a new line")
print("S: Save your edited text file")
print("Q: Quit")
while True:
response = input("Please choose an option: ").upper()
if response == "A":
line = input("Enter the new line to insert after the current line: ")
line = line + "\n"
fileList.insertAfter(line)
seeFile()
elif response == "B":
line = input("Enter the new line to insert before the current line: ")
line = line + "\n"
fileList.insertBefore(line)
seeFile()
elif response == "C":
line = fileList.getCurrent()
print("The current line is:", line)
elif response == "F":
first = fileList.first()
print("The first line is:", fileList.getCurrent())
elif response == "L":
last = fileList.last()
print("The last line is:", fileList.getCurrent())
elif response == "E":
try:
nextLine = fileList.next()
print("The next line is:", fileList.getCurrent())
except AttributeError:
print("You have reached the end of the file.")
elif response == "P":
try:
prevLine = fileList.previous()
print("The previous line is:", fileList.getCurrent())
except AttributeError:
print("You have reached the beginning of the file.")
elif response == "D":
fileList.remove()
seeFile()
elif response == "R":
item = input("Enter the line you would like put into the file: ")
item = item + "\n"
fileList.replace(item)
seeFile()
elif response == "S":
temp = fileList.first()
while temp!= None:
result = str(temp.getData())
myFile.write(result)
temp = temp.getNext()
myFile.close()
print("Your file has been saved.")
print()
elif response == "Q":
print("Thank you for using TextEd!")
break
else:
print("That is not a valid option.")
main()
절약을 제외하고 모든 것이 훌륭하게 작동합니다. 다른 점은 myFile.close()에 도착하면 "목록 객체에 특성이 없습니다"라는 오류가 발생한다는 것입니다.
더 많은 코드를보고 싶다면 말해주세요! 나는 이것이 아마 "완벽한"코드가 아니라는 것을 알고있다. 그래서 나와 맺어 라. 감사!
elif response == "S":
myFile = open(fileName,"w")
fileList.first()
current = fileList.getCurrent()
try:
for x in range(len(fileList)):
myFile.write(str(current))
current = fileList.next()
current = fileList.getCurrent()
print(current)
except AttributeError:
myFile.close()
print("Your file has been saved.")
print()
오케이, 마침내 위 코드로 작업하게되었습니다. 나는 아마도 이것이 아마도 그것을 작성하는 가장 추악한 방법에 관한 것이지만 적어도 작동한다는 것을 확신합니다!
팁 주셔서 감사합니다! 그 변화를 만들었고 위의 코드에 반영되었습니다. 더 이상 오류가 발생하지 않지만 저장하면 아무 것도 실제로 파일에 저장되지 않습니다. 나는 여전히 원본 파일을 가지고 있거나 새 파일을 만든 경우 빈 파일이 있습니다. 추측 해봐? :) – AbigailB
쓰기를 위해 파일을 여는 새 명령을 추가하려고 시도했지만 도움이되지 않았습니다. 내가 기존 파일에서 그 파일을 만들었을 때 예상했던 내용이 지워졌지만 새 목록을 파일에 쓰지 않았습니다. – AbigailB
이전의 대답을 수정했습니다 (위 참조). –