Python实现扫描指定目录下的子目录及文件的方法
本文介绍了使用Python来扫描指定目录下的文件,或者匹配指定后缀和前缀的函数。步骤如下:
如果要扫描指定目录下的文件,包括子目录,需要调用scan_files("/export/home/test/")
如果要扫描指定目录下的特定后缀的文件(比如jar包),包括子目录,调用scan_files("/export/home/test/", postfix=".jar")
如果要扫描指定目录下的特定前缀的文件(比如test_xxx.py),包括子目录,调用scan_files("/export/home/test/", postfix="test_")
具体实现代码如下:
#!/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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How do Python scripts clear output to cursor position at a specific location? When writing Python scripts, it is common to clear the previous output to the cursor position...

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

Regarding the problem of removing the Python interpreter that comes with Linux systems, many Linux distributions will preinstall the Python interpreter when installed, and it does not use the package manager...

Exploration of cracking verification codes using Python In daily network interactions, verification codes are a common security mechanism to prevent malicious manipulation of automated programs...

How to use Go or Rust to call Python scripts to achieve true parallel execution? Recently I've been using Python...

Python ...
