我不明白为什么我只在循环写入的日志文件中得到单词和ln的第一个匹配项(有50个或更多匹配项)。而且它的结构不像我在屏幕上打印时那样。下面是代码。谢谢!我正在写的文件中的结果:34343836393970642regex = re.compile(r'(?:3\d){6}')for root,dirname, files in os.walk(directory): for file in files: if file.endswith(".log") or file.endswith(".txt"): f = open(os.path.join(root,file)) for i, line in enumerate(f.readlines()): searchedstr = regex.findall(line) ln = str(i) for word in searchedstr: print "\nString found: " + word print "Line: " + ln print "File: " + os.path.join(root,file) print " " logfile = open('result3.log', 'w') logfile.write(word + '\n' + ln) logfile.close() f.close() 最佳答案 这是你的问题: logfile = open('result3.log', 'w') logfile.write(word + '\n' + ln) logfile.close()每次这样打开日志文件时,它都会擦除之前和之后的所有内容。从文件开头开始写入。您可以将open更改为 logfile = open('result3.log', 'a')(“ a”代表“ append”),或者-最好-在最外层循环之外仅打开一次logfile,如下所示:regex = re.compile(r'(?:3\d){6}')with open('result3.log', 'w') as logfile: for root, dirname, files in os.walk(directory): # ... logfile.write(word + '\n' + ln)with会为您关闭文件,因此您不需要显式的logfile.close()。 (最好是使用with打开f的样式也更好,如果只是这样,则f.close()不会在嵌套循环的下面晃来晃去。)(其他附录:enumerate(f.readlines())与,但速度较慢。)关于python - 将搜索结果从for循环写入文件只能得到一行(一个结果),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5872857/
10-12 04:00