检查python文件中是否存在行
如何使用Python检查文件中是否存在行,如果不存在行,如何将行写入文件 这是我目前的尝试 logfile = open('ip.log', 'a+') while 1: line = logfile.readline() #line.replace("\n", "") print line if line == str(self.CLIENT_HOST): print "Line Found Skipping" else: logfile.write(str(self.CLIENT_HOST)+"\n") if not line: print "EOF Reached" break print line logfile.close() logfile=open('ip.log','a+')) 而1: line=logfile.readline() #行。替换(“\n”和“”) 打印行 如果line==str(self.CLIENT\u HOST): 打印“发现跳过的行” 其他: logfile.write(str(self.CLIENT\u HOST)+“\n”) 如果不是直线: 打印“达到EOF” 打破 打印行 logfile.close() cheers将open('ip.log','a+')更改为open('ip.log','r'),然后稍后再次写入该文件或写入新文件。否则,只会使文件无限长检查python文件中是否存在行,python,Python,如何使用Python检查文件中是否存在行,如果不存在行,如何将行写入文件 这是我目前的尝试 logfile = open('ip.log', 'a+') while 1: line = logfile.readline() #line.replace("\n", "") print line if line == str(self.CLIENT_HOST): print "Line Found S
logfile = open('ip.log', 'r')
loglist = logfile.readlines()
logfile.close()
found = False
for line in loglist:
if str(self.CLIENT_HOST) in line:
print "Found it"
found = True
if not found:
logfile = open('ip.log', 'a')
logfile.write(str(self.CLIENT_HOST)+"\n")
logfile.close()
这是我的第一个快速解决方案。非常不干净,还不成熟,但应该可以工作。使用python过滤器:
file = open('ip.log', 'r')
flines = file.readlines()
res = filter(lambda x: self.CLIENT_HOST in x, flines)
if len(res) == 0:
file.write(str(self.CLIENT_HOST)+"\n")
file.close()
通过对这些行进行迭代,可以在找到匹配项时停止加载文件,并避免将整个文件保存在内存中
def log_host(self):
host = str(self.CLIENT_HOST)
with open('ip.log', 'r+') as logfile:
for line in logfile:
if line.strip() == host:
return
# Move to the end of the file:
logfile.seek(0, 2)
logfile.write(host + "\n")
要在日志文件中附加客户端主机字符串(如果该字符串尚未出现),可以:
with open('ip.log', 'r+') as f:
for line in f:
if self.CLIENT_HOST in line:
break
else: # not found
print >>f, self.CLIENT_HOST
注意:
else
语句的缩进不是错误。Python的一个特性是允许for
和while
循环使用else
子句。如果break
语句没有在循环中执行,它就会运行。我认为这应该可以工作,而且它比其他任何答案都更整洁、更健壮。如果没有,则可能需要打开另一个文件进行写入(第一个文件'r'
,第二个文件'a'
)。我还使用了x.rstrip('\r\n')
和=
而不是中的,以确保它是正确的。我不知道您的客户机主机变量是什么。如果您的客户机\u主机
已经是str,请扔掉第一行,将其他行改回直接引用它
value = str(self.CLIENT_HOST)
with open('ip.log', 'a+') as f:
if not any(value == x.rstrip('\r\n') for x in f):
f.write(value + '\n')
可能是这样的
line="the line you are searching for"
logfile = open('ip.log', 'r')
loglist = logfile.readlines()
logfile.close()
if line not in loglist:
loglist.append(line)
new_logfile = open("pathToTheFile/logfile", 'w')
for lines in loglist:
new_logfile.write(lines)
请注意,最好使用内置函数,如readlines()和for。。语法。While(1)更容易出错。你根本不应该使用While 1:它是一个神奇的数字用法。相反,如果需要,使用while True:。@Andrej:我同意。然而,仅仅出于好奇,while1:
在Python 2中实际上更有效,因为True
执行查找(它不是Python 3中的保留字),而1
已知为True-因此字节码的形成实际上没有为while1:
创建块。为了观察,创建函数并比较dis.dis(func)
@Chris:interest!我记得读过一次关于python中True的系谱,但我不知道这一点。我想还有一个理由去Python3。非常不干净和低效。完全被低估了,在我看来是上等的解决方案。谢谢,模式应该是"r+"和"a+",我用不上Python3@tamerlahaprint>>f,…
表明这是一个Python 2代码。虽然r+
看起来应该更合适。您不是已经在文件末尾了吗,因为您刚刚读取了每一行吗?OS X可能需要额外的f.seek(0),因为在“a+”模式下打开后,文件指针位于文件末尾。