'Reading Error line from multiple files in python
I want read error line form multiple files using python. these files are in .log format.
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. 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 ?
Solution 1:[1]
Use nested for loops to check each file.
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()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
