Python 3: 从基于游标的列表写入文件

2 投票
1 回答
1236 浏览
提问于 2025-04-17 16:56

这是一个作业,我对Python还很陌生。我写了一个文本编辑器程序,使用了一个双向光标的列表类。用户可以打开一个已有的文件进行编辑,或者创建一个新文件,并为这个文件创建一个基于光标的列表。最后,我希望用户能够把他们所做的更改保存回文件中。不过我遇到了一些错误,不知道该怎么办。任何建议都很感激!

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()时,出现了一个错误,提示“列表对象没有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()

好的,我终于用上面的代码让它工作了。我知道这可能是写得最丑陋的方式,但至少它能运行!

1 个回答

3

首先,你在这里给 myFile 赋值:

        myFile = open(fileName, 'r')

这时候,myFile 是一个文件对象。不过,接下来你做了这个:

        myFile = myFile.readlines()

现在 myFile 变成了一个包含文件中所有行的列表,所以它不能再被关闭了。你可以把 myFile.readlines() 的结果赋值给一个不同的变量,这样就没问题了。

关于文件的输入/输出,你可以查看 这份文档

在写这段内容的时候, fileList 也是空的,因为当你打开文件准备写入时,你也在这里把 fileList 设置成了一个新的 CursorBasedList

elif response == "N":
        fileName = input("What would you like to name your file?: ")
        fileList = CursorBasedList() # <- Here
        myFile = open(fileName, "w")

如果你去掉那一行,应该就能正常工作了。

撰写回答