如何将我的输入输入到 python 中的文本文件中?

时间:2021-04-28 07:50:31

标签: python file

我正在尝试创建一个程序,该程序可以将输入保存到一个新文件中,如果它尚不存在并且它必须始终位于新行上。如果输入是空格,则必须忽略它。然而我想不通。

def saving(textr):
    with open("abc.txt", "a+") as file_object:
        file_object.seek(0)
        data = file_object.read(100)
        if textr == "" or textr.isspace():
            return textr
        else:
            for line in file_object:
                if textr in line:
                    break
                elif len(data) > 0:
                    file_object.write("\n")
                file_object.write(textr)


textr = input("Enter your text: ")
saving(textr)

以及我尝试过的另一种方式:

textr = ""
def saving(textr):
    textr = input("Enter your text: ")
    with open("abc.txt", "a+") as file_object:
        file_object.seek(0)
        data = file_object.read(100)
        if textr == "" or textr.isspace():
            return textr
        else:
            for line in file_object:
                if textr in line:
                    break
                else:
                    if len(data) > 0:
                        file_object.write("\n")
                    file_object.write(textr)
                    print ("done")


saving(textr)

1 个答案:

答案 0 :(得分:1)

试试这段代码,我写了一些注释以使其不言自明:

def update_file(text):
    # If the text is empty or only contains whitespaces,
    # we exit the function
    if not text.strip():
        return

    with open("abc.txt", "a+") as file_object:
        # We put the cursor at the beggining of the
        # file
        file_object.seek(0)

        # We get all the lines from the file. As every
        # line ends with a "\n" character, we remove
        # it from all lines
        lines = [line.strip() for line in file_object.readlines()]

        # As we read all the lines, the cursor is now
        # at the end and we can append content, so:

        # We first check if the entered text is contained
        # in the file, and if so we exit the function
        if text in lines:
            return

        # We write the text in the file
        file_object.write('{}\n'.format(text))

text = input("Enter your text: ")
update_file(text)