检查文件是否存在,如果存在则追加记录
我正在创建一个日志文件,里面记录每一行的信息。
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()
如果文件不存在,代码就会出错。
5 个回答
0
检查一个文件是否存在可能会引发竞争条件,也就是说,在你检查文件是否存在的过程中,其他程序可能会在你检查之后创建这个文件或者删除它,这样就会导致很严重的错误。为了避免这种情况,你应该使用:
if open('path\to.filename', 'a+') != '':
stuff_if_exists
else:
stuff_if_not_exists
0
你是以 r+
模式打开文件的,这意味着你假设这个文件是存在的。而且,如果你打算在文件上写东西,你应该用 a+
模式来打开它(这段解释是借用ndpu的说法)。这样,你的代码就可以变成:
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
0
试试这个:
import os
if os.path.exists(my_file):
print 'file does not exist'
# some processing
else:
print 'file exists'
# some processing
1
下面的代码可以正常运行:
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()
6
使用 'a+'
模式:
logFile = open('Dump.log', 'a+')
说明:
a+
这个模式是用来同时读取和写入文件的。如果文件不存在,它会被创建。打开文件后,光标会自动移动到文件的末尾。之后你写入文件的内容,都会添加到当前文件的末尾,不管你之前有没有用其他方法(比如 fseek(3))改变过光标的位置。