'I want to serach some text on multiple files [CLOSED}
In one directory i have lots of file and in every 4 hours new file named as filename_date is getting created so i just want to check on last 5 created files only. for example
-rw-r--r-- 1 root root 5686 Jan 31 06:12 process_list.txt_20220131_061218.txt
-rw-r--r-- 1 root root 8921 Jan 31 07:00 process_list.txt_20220131_070001.txt
-rw-r--r-- 1 root root 13950 Jan 31 08:00 process_list.txt_20220131_080001.txt
-rw-r--r-- 1 root root 13191 Jan 31 12:00 process_list.txt_20220131_120002.txt
-rw-r--r-- 1 root root 13093 Jan 31 16:00 process_list.txt_20220131_160002.txt
-rw-r--r-- 1 root root 13335 Jan 31 20:00 process_list.txt_20220131_200002.txt
-rw-r--r-- 1 root root 13290 Feb 1 00:00 process_list.txt_20220201_000002.txt
-rw-r--r-- 1 root root 19205 Feb 1 02:00 process_list.txt_20220201_020001.txt
-rw-r--r-- 1 root root 9358 Feb 1 04:00 process_list.txt_20220201_040001.txt
-rw-r--r-- 1 root root 17036 Feb 1 07:00 process_list.txt_20220201_070001.txt
-rw-r--r-- 1 root root 17069 Feb 1 08:00 process_list.txt_20220201_080002.txt
-rw-r--r-- 1 root root 17234 Feb 1 12:00 process_list.txt_20220201_120002.txt
-rw-r--r-- 1 oracle oinstall 17275 Feb 1 12:00 process_list_previous.txt
-rw-r--r-- 1 oracle oinstall 17328 Feb 1 12:10 process_list.txt
This is list of file in my directory i just want to traverse "process_list.txt", "process_list_previous.txt", "process_list.txt_20220201_120002.txt", "process_list.txt_20220201_080002.txt" and "process_list.txt_20220201_070001.txt" . Only these files i want to traverse and search something. Is there any module which can help me to restrict number of files need to traverse in python
Solution 1:[1]
I am able to figure out this problem and fixed it for now. Adding code snippet
files = glob.glob(process_list_file_path)
# Need to check file is avail or not in files
if len(files) != 0:
files.sort(key=os.path.getmtime)
# If length is equal or less than 5 then
latest=files[-5:]
if len(latest) <= 5:
print("\n".join(latest))
for fn in latest:
with open(fn) as k:
lines = fn.readlines()
for line in lines:
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 | Keshav |
