3

I am creating a log file with line by line records.

1- If file does not exist, it should create file and append header row and the record 2- if it exists, check the text timeStamp in first line. If it exist then append the record otherwise add header columns and record itself

I tried both w,a and r+; nothing worked for me. Below is my code:

logFile = open('Dump.log', 'r+')
datalogFile = log.readline()
if 'Timestamp' in datalogFile:
    logFile.write('%s\t%s\t%s\t%s\t\n'%(timestamp,logread,logwrite,log_skipped_noweight))
    logFile.flush()
else:
    logFile.write('Timestamp\t#Read\t#Write\t#e\n')
    logFile.flush()
    logFile.write('%s\t%s\t%s\t%s\t\n'%(timestamp,logread,logwrite,log_skipped))
    logFile.flush()

Code fails if file don't exist

Volatil3
  • 14,253
  • 38
  • 134
  • 263

5 Answers5

6

Use 'a+' mode:

logFile = open('Dump.log', 'a+')

description:

a+
Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar

ndpu
  • 22,225
  • 6
  • 54
  • 69
1

Following code would work:

import os
f = open('myfile', 'ab+') #you can use a+ if it's not binary
f.seek(0, os.SEEK_SET)
print f.readline() #print the first line
f.close()
venpa
  • 4,268
  • 21
  • 23
0

Try this:

import os
if os.path.exists(my_file):
    print 'file does not exist'
    # some processing
else:
    print 'file exists'
    # some processing
wap26
  • 2,180
  • 1
  • 17
  • 32
0

You're opening the file in r+ mode which means you assume the file exists. Also, if you intend the write on the file, you should open it with a+ mode (unashamedly stealing ndpu's explanation) Your code would become:

    logFileDetails = []
    with open("Dump.log","a+") as logFile:
        logFileDetails = logFile.readLines()
        if logFileDetails and "Timestamp" in logFileDetails:
            pass # File exists, write your stuff here
        else:
            pass # Log file doesn't exist, write timestamp here
Tejas Pendse
  • 551
  • 6
  • 19
0

Checking a file existence introduces a race condition, i.e. another process can create it or delete it after the check returns false or true, respectively, creating heavy bugs. You should instead use:

if open('path\to.filename', 'a+') != '':
  stuff_if_exists
else:
  stuff_if_not_exists
wallabra
  • 412
  • 8
  • 17