检查文件是否存在,然后追加记录

2024-09-29 23:30:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我试过w,a和r+,但都不管用。以下是我的代码:

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

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


Tags: 文件代码文本log标题记录timestampwrite
3条回答

使用'a+'模式:

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

以下代码将起作用:

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

试试这个:

import os
if os.path.exists(my_file):
    print 'file does not exist'
    # some processing
else:
    print 'file exists'
    # some processing

相关问题 更多 >

    热门问题