Python recursively traverses folders and prints instances of file paths that meet the conditions,
Question:Use coroutine to traverse the directory, whether all the sub-files and files in the sub-Folder contain a certain field value, and print the absolute path of the file that meets the conditions.
#! /User/bin/env python #-*-coding: UTF-8-*-# grep-rl "python" D: \ devtools \ workspace \ python \ aaaimport osdef init (func ): def wrapper (* args, ** kwargs): res = func (* args, ** kwargs) res. send (None) return res return wrapper @ initdef search (target): 'Find the absolute path of the file' while True: dir_name = yield g = OS. walk (dir_name) for I in g: for j in I [-1]: file_path = "% s \ % s" % (I [0], j) target. send (file_path) @ initdef get_file_handle (target): 'Get the file handle 'while True: file_path = yield with open (file_path) as f: target. send (file_path, f) @ initdef cat_file (target): 'read The file' while True: file_path, f = yield for line in f: target. send (file_path, line) @ initdef printer (pattern): 'print the file that meets the filtering condition's s = set () while True: file_path, line = yield if pattern in line: if file_path not in s: print (file_path) s. add (file_path) g = search (get_file_handle (cat_file (printer ("python") g. send ("D: \ devtools \ workspace \ python \ aaa ")
After the decorator is used, you do not need to execute. send (None) every time. The parameter target receives a generator.
The whole programming adopts a process-oriented approach.
The entire process needs to be designed for the process.
The advantage is: a. The architecture is clearer; B. The complexity of the program is simplified.
Disadvantage: not scalable (internal coupling is too high)
Specific application scenarios: software that does not need to change for a long time. Such as System
In the above example, python recursively traverses folders and prints the file path instances that meet the conditions. This is all the content shared by Alibaba Cloud. I hope you can provide a reference and support for the customer's home.