search
HomeBackend DevelopmentPython TutorialPython list all files in a folder and its subdirectories

python简介

Python是一种解释型、面向对象、动态数据类型的高级程序设计语言。

Python由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年。

像Perl语言一样, Python 源代码同样遵循 GPL(GNU General Public License)协议。

>>> import os
>>> for i in os.walk("."):
... print i[0],"\n##",i[1],"\n##",i[2]
... 
. #当前目录
## ['fa', 'out'] #当前目录中的子目录 
## ['meta_rna.sh', 'nohup.out', 'log.cpu', 'blast_seq.py']
./fa # 第一个子目录
## [] # 第一个子目录中的目录
## ['assemblyar_new_2.faa']
./out # 第二个子目录
## [] # 第二个子目录中的目录
## ['assemblyar_new_2.faa.coord', 'assemblyar_new_2.faa.mask', 'assemblyar_new_2.faa.seq', 'result_1.xm', 'result.xml', 'blast_seq.py']

也可以用 os.path.walk, 先定义一个访问文件夹的函数, VisitDir

>>> def VisitDir(arg, dirname, names):
... for filespath in names:
... print os.path.join(dirname, filespath)
... 
>>> path="."
>>> os.path.walk(path, VisitDir, ())
./meta_rna.sh
./fa
./out
./nohup.out
./log.cpu
./blast_seq.py
./fa/assemblyar_new_2.faa
./out/assemblyar_new_2.faa.coord
./out/assemblyar_new_2.faa.mask
./out/assemblyar_new_2.faa.seq
./out/result_1.xm
./out/result.xml
./out/blast_seq.py
>>> os.getcwd()
'/home/served_pro/Find_nick'
>>> abs_path= os.getcwd()
>>> os.path.walk(abs_path, VisitDir, ())
/home/served_pro/Find_nick/meta_rna.sh
/home/served_pro/Find_nick/fa
/home/served_pro/Find_nick/out
/home/served_pro/Find_nick/nohup.out
/home/served_pro/Find_nick/log.cpu
/home/served_pro/Find_nick/blast_seq.py
/home/served_pro/Find_nick/fa/assemblyar_new_2.faa
/home/served_pro/Find_nick/out/assemblyar_new_2.faa.coord
/home/served_pro/Find_nick/out/assemblyar_new_2.faa.mask
/home/served_pro/Find_nick/out/assemblyar_new_2.faa.seq
/home/served_pro/Find_nick/out/result_1.xm
/home/served_pro/Find_nick/out/result.xml
/home/served_pro/Find_nick/out/blast_seq.py

下面给大家介绍python列出文件夹下的所有文件

#方法1:使用os.listdir
import os
for filename in os.listdir(r'c:\\windows'):
print filename
#方法2:使用glob模块,可以设置文件过滤
import glob
for filename in glob.glob(r'c:\\windows\\*.exe'):
print filename
#方法3:通过os.path.walk递归遍历,可以访问子文件夹
import os.path
def processDirectory ( args, dirname, filenames ):
print 'Directory',dirname
for filename in filenames:
print ' File',filename
os.path.walk(r'c:\\windows', processDirectory, None )
#方法4:非递归
import os
for dirpath, dirnames, filenames in os.walk('c:\\\\winnt'):
print 'Directory', dirpath
for filename in filenames:
print ' File', filename

另外,判断文件与目录是否存在:

import os
os.path.isfile('test.txt') #如果不存在就返回False
os.path.exists(directory) #如果目录不存在就返回False

以上所述是小编给大家介绍的Python列出一个文件夹及其子目录的所有文件,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对PHP中文网的支持!

更多Python列出一个文件夹及其子目录的所有文件相关文章请关注PHP中文网!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How Do I Use Beautiful Soup to Parse HTML?How Do I Use Beautiful Soup to Parse HTML?Mar 10, 2025 pm 06:54 PM

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Mathematical Modules in Python: StatisticsMathematical Modules in Python: StatisticsMar 09, 2025 am 11:40 AM

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti

Serialization and Deserialization of Python Objects: Part 1Serialization and Deserialization of Python Objects: Part 1Mar 08, 2025 am 09:39 AM

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

How to Perform Deep Learning with TensorFlow or PyTorch?How to Perform Deep Learning with TensorFlow or PyTorch?Mar 10, 2025 pm 06:52 PM

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

How to solve the permissions problem encountered when viewing Python version in Linux terminal?How to solve the permissions problem encountered when viewing Python version in Linux terminal?Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

What are some popular Python libraries and their uses?What are some popular Python libraries and their uses?Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

Scraping Webpages in Python With Beautiful Soup: Search and DOM ModificationScraping Webpages in Python With Beautiful Soup: Search and DOM ModificationMar 08, 2025 am 10:36 AM

This tutorial builds upon the previous introduction to Beautiful Soup, focusing on DOM manipulation beyond simple tree navigation. We'll explore efficient search methods and techniques for modifying HTML structure. One common DOM search method is ex

How to Create Command-Line Interfaces (CLIs) with Python?How to Create Command-Line Interfaces (CLIs) with Python?Mar 10, 2025 pm 06:48 PM

This article guides Python developers on building command-line interfaces (CLIs). It details using libraries like typer, click, and argparse, emphasizing input/output handling, and promoting user-friendly design patterns for improved CLI usability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.