Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Open a file, search then append, if not exist

Tags:

python

I am trying to append a string to a file, if the string doesn't exit in the file. However, opening a file with a+ option doesn't allow me to do at once, because opening the file with a+ will put the pointer to the end of the file, meaning that my search will always fail. Is there any good way to do this other than opening the file to read first, close and open again to append?

In code, apparently, below doesn't work.

file = open("fileName", "a+")

I need to do following to achieve it.

file = open("fileName", "r")
... check if a string exist in the file
file.close()

... if the string doesn't exist in the file
file = open("fileName", "a")
file.write("a string")
file.close()
like image 988
Yui Park Avatar asked Feb 07 '15 17:02

Yui Park


2 Answers

To leave the input file unchanged if needle is on any line or to append the needle at the end of the file if it is missing:

with open("filename", "r+") as file:
    for line in file:
        if needle in line:
           break
    else: # not found, we are at the eof
        file.write(needle) # append missing data

I've tested it and it works on both Python 2 (stdio-based I/O) and Python 3 (POSIX read/write-based I/O).

The code uses obscure else after a loop Python syntax. See Why does python use 'else' after for and while loops?

like image 170
jfs Avatar answered Oct 22 '22 14:10

jfs


You can set the current position of the file object using file.seek(). To jump to the beginning of a file, use

f.seek(0, os.SEEK_SET)

To jump to a file's end, use

f.seek(0, os.SEEK_END)

In your case, to check if a file contains something, and then maybe append append to the file, I'd do something like this:

import os

with open("file.txt", "r+") as f:
    line_found = any("foo" in line for line in f)
    if not line_found:
        f.seek(0, os.SEEK_END)
        f.write("yay, a new line!\n")
like image 43
Carsten Avatar answered Oct 22 '22 12:10

Carsten