file accessing in python
Question: i searched for the answer couldn't get it.

i have the following code,

    
    
    filePointer = open(r'c:\temp\logFile.txt', 'w')
    filePointer.write(str( datetime.datetime.now()) + 'entered into table \n' )
    

but before i enter the above line into file, i want to check if it is already
present in it. i can read the file and string compare and all, but I'm looking
for a better way, help me out if there is any.


Answer: Shrinidhi,

I believe this what you're looking for. First you need to not use `'w'` on
`open` since that will cause any new writing to the file to replace the
current contents. Instead you should use `'a'` or `'a+'` to append to the
file. See code below:

    
    
    from datetime import datetime
    
    line_to_add = 'def'
    
    with open('file.txt', 'a+') as openfile:
        if not (item for item in openfile if line_to_add not in line):
            openfile.write(str(datetime.now()) + " " + line_to_add + ' \n')
    

This will check if the line is already in the file. If it's not there it will
add it with a time stamp.

You'll have to string compare, but at lease it's using a generator to do so.

