关于python:检查文件是否存在,然后追加记录

Checking file if exist then append record

我正在创建一个具有逐行记录的日志文件。

1-如果文件不存在,则应创建文件并附加标题行和记录2-如果存在,请检查第一行中的文本timeStamp。如果它存在,那么附加记录,否则添加标题列和记录本身。

我尝试了w,a和r+;没有什么对我有用。以下是我的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
logFile = open('Dump.log', 'r+')
datalogFile = log.readline()
if 'Timestamp' in datalogFile:
    logFile.write('%s\t%s\t%s\t%s\t
'
%(timestamp,logread,logwrite,log_skipped_noweight))
    logFile.flush()
else:
    logFile.write('Timestamp\t#Read\t#Write\t#e
'
)
    logFile.flush()
    logFile.write('%s\t%s\t%s\t%s\t
'
%(timestamp,logread,logwrite,log_skipped))
    logFile.flush()

如果文件不存在,则代码失败


使用'a+'模式:

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

描述:

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


以下代码可以工作:

1
2
3
4
5
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()


检查文件是否存在会引入竞争条件,即另一个进程可以在检查返回false或true后分别创建或删除该文件,从而导致严重的错误。您应该使用:

1
2
3
4
if open('path\to.filename', 'a+') != '':
  stuff_if_exists
else:
  stuff_if_not_exists

您正在以r+模式打开文件,这意味着您假定该文件存在。另外,如果你想在文件上写东西,你应该用a+模式打开它(毫不客气地窃取ndpu的解释)。您的代码将变为:

1
2
3
4
5
6
7
    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

试试这个:

1
2
3
4
5
6
7
import os
if os.path.exists(my_file):
    print 'file does not exist'
    # some processing
else:
    print 'file exists'
    # some processing