Python implements the method of scanning subdirectories and files in a specified directory
- 2020-04-02 13:49:52
- OfStack
This article describes using Python to scan files in a specified directory, or to match functions that specify suffixes and prefixes. The steps are as follows:
To scan files in the specified directory, including subdirectories, call scan_files("/export/home/test/")
If you want to scan files(such as jars) in a specified directory with a particular suffix, including subdirectories, call scan_files("/export/home/test/", postfix=".jar")
If you want to scan files with a specific prefix (such as test_xxx.py) in the specified directory, including subdirectories, call scan_files("/export/home/test/", postfix="test_")
The specific implementation code is as follows:
#!/usr/bin/env python
#coding=utf-8
import os
def scan_files(directory,prefix=None,postfix=None):
files_list=[]
for root, sub_dirs, files in os.walk(directory):
for special_file in files:
if postfix:
if special_file.endswith(postfix):
files_list.append(os.path.join(root,special_file))
elif prefix:
if special_file.startswith(prefix):
files_list.append(os.path.join(root,special_file))
else:
files_list.append(os.path.join(root,special_file))
return files_list