search
HomeBackend DevelopmentPython Tutorialpython中遍历文件的3个方法

今天写一个在windows下批量修改文件名的python脚本,用到文件的遍历。用python进行文件遍历有多种方法,这里列举并说明一下。

os.path.walk()

这是一个传统的用法。

walk(root,callable,args)方法有三个参数:要遍历的目录,回调函数,回调函数的参数(元组形式)。

调用的过程是遍历目录下的文件或目录,每遍历一个目录,调用回调函数,并把args作为参数传递给回调函数。

回调函数定义时也有三个参数,比如示例中的func中的三个参数,分别为walk传来的参数、目录的路径、目录下的文件列表(只有文件名,不是完整路径)。请看示例:

复制代码 代码如下:

import os
s = os.sep #根据unix或win,s为\或/
root = "d:" + s + "ll" + s #要遍历的目录

def func(args,dire,fis): #回调函数的定义
    for f in fis:
        fname = os.path.splitext(f)  #分割文件名为名字和扩展名的二元组
        new = fname[0] + 'b' + fname[1]  #改名字
        os.rename(os.path.join(dire,f),os.path.join(dire,new)) #重命名

os.path.walk(root,func,()) #遍历

这种方法在使用时有个问题,不能递归遍历下一层(这点我还不确定,欢迎指正)。

python的高级版本中加入了os.walk(),比这个好用。

os.walk()

原型为:os.walk(top, topdown=True, onerror=None, followlinks=False)

我们一般只使用第一个参数。(topdown指明遍历的顺序)
该方法对于每个目录返回一个三元组,(dirpath, dirnames, filenames)。第一个是路径,第二个是路径下面的目录,第三个是路径下面的非目录(对于windows来说也就是文件)。请看示例:

复制代码 代码如下:

import os
s = os.sep
root = "d:" + s + "ll" + s 

for rt, dirs, files in os.walk(root):
    for f in files:
        fname = os.path.splitext(f)
        new = fname[0] + 'b' + fname[1]
        os.rename(os.path.join(rt,f),os.path.join(rt,new))

这种方式可以递归遍历所有的文件。

listdir

可以使用os模块下的几个方法组合起来进行遍历。请看示例:

复制代码 代码如下:

import os
s = os.sep
root = "d:" + s + "ll" + s

for i in os.listdir(root):
    if os.path.isfile(os.path.join(root,i)):
        print i

这里需要注意的是,其中的i是目录或文件名,不是完整的路径,在使用时要结合os.path.join()方法还原完整路径。

遍历搞定之后,文件名的修改可以使用正则表达式做一些高级的处理。

另外,还可以使用os.system(cmd)来调用shell里面的相关命令对文件进行处理,很好很强大。

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
Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

For loop and while loop in Python: What are the advantages of each?For loop and while loop in Python: What are the advantages of each?May 13, 2025 am 12:01 AM

Forloopsareadvantageousforknowniterationsandsequences,offeringsimplicityandreadability;whileloopsareidealfordynamicconditionsandunknowniterations,providingcontrolovertermination.1)Forloopsareperfectforiteratingoverlists,tuples,orstrings,directlyacces

Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),