1

how do you do this series of actions in python?

1) Create a file if it does not exist and insert a string

2) If the file exists, search if it contains a string

3) If the string does not exist, hang it at the end of the file

I'm currently doing it this way but I'm missing a step

EDIT with this code every time i call the function seems that the file does not exist and overwrite the older file

def func():
if not os.path.exists(path):
    #always take this branch
    with open(path, "w") as myfile:
        myfile.write(string)
        myfile.flush()
        myfile.close()
else:
    with open(path) as f:
        if string in f.read():
            print("string found")
        else:
            with open(path, "a") as f1:
                f1.write(string)
                f1.flush()
                f1.close()
    f.close()

2 Answers 2

6

Try this:

with open(path, 'a+') as file:
    file.seek(0)
    content = file.read()
    if string not in content:
        file.write(string)

seek will move your pointer to the start, and write will move it back to the end.

Edit: Also, you don't need to check the path. Example:

>>> f = open('example', 'a+')
>>> f.write('a')
1
>>> f.seek(0)
0
>>> f.read()
'a'

file example didn't exist, but when I called open() it was created. see why

Sign up to request clarification or add additional context in comments.

3 Comments

I tried your version too but I think I have problem with os.path.exists since always take the does not exists branch
a+ and w+ will automatically create new files when writing a new file, so you don't need to check if a path exists tutorialspoint.com/python/python_files_io.htm
The code I provided is already complete. I just edited my answer with new information.
1

You don't need to reopen the file if you have not yet closed it after initially opening it. Use "a" when opening the file in order to append to it. So... "else: with open(path, "a") as f: f.write(string)". Try that

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.