Home  >  Article  >  Backend Development  >  Python批量修改文件后缀的方法

Python批量修改文件后缀的方法

WBOY
WBOYOriginal
2016-06-16 08:45:271243browse

近期下载了很多各种教程, 但是不幸的是后缀名都是 ".mp4", 而本人喜欢 ".rmvb" 后缀,由于有轻微洁癖, 受不了后面的 ".mp4" 缀, 但是手动修改又太过繁琐, 所以用近期刚学的 Python 来偷懒吧 !   : )

如图为程序运行前的文件名

Python批量修改文件后缀的方法

我们要做的呢, 就是在当前目录下,新建一个python文件, 如上图 demo2.py 然后用编辑器打开敲入如下代码:

复制代码 代码如下:

import os

# 列出当前目录下所有的文件
files = os.listdir(".")      

for filename in files:
    portion = os.path.splitext(filename)
    # 如果后缀是.txt
    if portion[1] == ".mp4": 
        # 重新组合文件名和后缀名  
        newname = portion[0] + ".rmvb"  
        os.rename(filename,newname)

好了, 写好之后保存并运行你的程序吧!

不出意外,你会惊奇的发现:

Python批量修改文件后缀的方法

哈哈, 所有的".mp4" 后缀的文件都该成".rmvb"的后缀啦!!!  

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