1

I am trying to create a program that saves input to a new file if it isn't there yet and it must always be on a new line. If the input is a whitespace it has to ignore it. Yet I cannot figure it out.

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)

and another way I have tried it:

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
  • What's your Error message? Commented Apr 28, 2021 at 8:05

1 Answer 1

1

Try this code, I wrote some comments in order to make it self-explanatory:

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.