python中遍历文件的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里面的相关命令对文件进行处理,很好很强大。

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



Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

Oracle database file structure includes: data file: storing actual data. Control file: Record database structure information. Redo log files: record transaction operations to ensure data consistency. Parameter file: Contains database running parameters to optimize performance. Archive log file: Backup redo log file for disaster recovery.

Oracle database login involves not only username and password, but also connection strings (including server information and credentials) and authentication methods. It supports SQL*Plus and programming language connectors and provides authentication options such as username and password, Kerberos and LDAP. Common errors include connection string errors and invalid username/passwords, while best practices focus on connection pooling, parameterized queries, indexing, and security credential handling.

This article will explain how to improve website performance by analyzing Apache logs under the Debian system. 1. Log Analysis Basics Apache log records the detailed information of all HTTP requests, including IP address, timestamp, request URL, HTTP method and response code. In Debian systems, these logs are usually located in the /var/log/apache2/access.log and /var/log/apache2/error.log directories. Understanding the log structure is the first step in effective analysis. 2. Log analysis tool You can use a variety of tools to analyze Apache logs: Command line tools: grep, awk, sed and other command line tools.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

The hiding place of Oracle database on the C drive: Registry: Use the registry editor to search for "Oracle" to find information including installation path, service name, etc. File system: Oracle files are scattered in multiple locations in the C drive, including home directory, system files, temporary files, etc. Environment variables: The environment variables set by Oracle (such as ORACLE_HOME, ORACLE_SID) point to the installation directory and instance name. Careful action: When uninstalling Oracle, you not only need to delete files, but also clean the registry and services. It is recommended to use the official uninstall tool or seek professional help. Space management: Optimize disk space to avoid installing Oracle on C drive; clean temporary files regularly

The comparison between Laravel and Python in the development environment and ecosystem is as follows: 1. The development environment of Laravel is simple, only PHP and Composer are required. It provides a rich range of extension packages such as LaravelForge, but the extension package maintenance may not be timely. 2. The development environment of Python is also simple, only Python and pip are required. The ecosystem is huge and covers multiple fields, but version and dependency management may be complex.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.
