分享

Python批量重命名文件的方法

 海漩涡 2014-05-07

Python批量重命名文件的方法

用到了os的两个接口:

1、列出文件夹中的所有文件(也包含目录)

os.listdir(path)
Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.

Availability: Unix, Windows.

Changed in version 2.3: On Windows NT/2k/XP and Unix, if path is a Unicode object, the result will be a list of Unicode objects. Undecodable filenames will still be returned as string objects

2、对文件进行重命名

os.rename(src, dst)
Rename the file or directory src to dst. If dst is a directory, OSError will be raised. On Unix, if dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if dst already exists, OSError will be raised even if it is a file; there may be no way to implement an atomic rename when dst names an existing file.

Availability: Unix, Windows

1
2
3
4
5
6
7
8
9
import os
 
dirpath="D:/workbench//myfiles"
for fname in os.listdir(dirpath):
    newfname=fname[3:]
    newfpath="%s/%s"%(dirpath,newfname)
    oldfpath="%s/%s"%(dirpath,fname)
     
    os.rename(oldfpath, newfpath)

其实就是用os.listdir读取里面所有的文件,然后用os.rename进行文件重命名即可实现。

python的os模块官方介绍:http://docs./2/library/os.html

转载请注明来源:http://www./1397.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多