JayJona
JayJona

Reputation: 502

open or create file in python and append to it

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()

Upvotes: 1

Views: 6806

Answers (2)

Orlando
Orlando

Reputation: 242

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

Upvotes: 6

Tai Johnson
Tai Johnson

Reputation: 11

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

Upvotes: 1

Related Questions