[英]Reading Error line from multiple files in python
I want read error line form multiple files using python. these files are in.log format.我想使用 python 从多个文件中读取错误行。这些文件是 in.log 格式。
I can read error when I hardcode the path of a particular file.当我对特定文件的路径进行硬编码时,我可以读取错误。 Using below code
使用下面的代码
file_in = open('C:\\Users\\Rahul\\AppData\\Roaming\\JetBrains\\PyCharmCE2021.3\\test.log','r') # Read file
for line in file_in: # Loop every line
if 'ERROR' in line: # Search for ERROR in line
print(line) # Print line
else: # Remove INFO and WARN lines
pass # Print line
However I want to read it from multiple files at once.但是我想一次从多个文件中读取它。 like I have 5 files and I want to read error line in each of these files.
就像我有 5 个文件,我想读取每个文件中的错误行。 Below is code I am working.
下面是我正在工作的代码。
import glob
file_list = glob.glob('C:\\Users\\Rahul\\AppData\\Roaming\\JetBrains\\PyCharmCE2021.3\\*.log')
my_list = []
path = "C:\\Users\\Rahul\\AppData\\Roaming\\JetBrains\\PyCharmCE2021.3\\*.log"
for file in glob.glob(path):
print(file)
file_in=open('C:\\Users\\Rahul\\AppData\\Roaming\\JetBrains\\PyCharmCE2021.3\\outbrain_sample_failed.log','r') # Read file
for line in file_in: # Loop every line
if 'ERROR' in line: # Search for ERROR in line
print(line) # Print line
else: # Remove INFO and WARN lines
pass # Print line
However I am not able to read it.但是我无法阅读它。 any suggestion or help?
有什么建议或帮助吗?
Use nested for loops to check each file.使用嵌套的 for 循环来检查每个文件。
import glob
file_list = glob.glob('C:\\Users\\Rahul\\AppData\\Roaming\\JetBrains\\PyCharmCE2021.3\\*.log')
for file in filelist:
file_in = open(file, "r")
for line in file_in.readlines(): # Loop every line
if 'ERROR' in line: # Search for ERROR in line
print(line) # Print line
else: # Remove INFO and WARN lines
pass # Print line
file_in.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.