用python实现批量重命名文件的代码

WBOY
Release: 2016-06-16 08:47:03
Original
1286 people have browsed it

下面是最终代码 (windows下实现的)

复制代码 代码如下:

# -*- coding: cp936 -*-
import os
path = 'D:\\图片\\'
for file in os.listdir(path):
if os.path.isfile(os.path.join(path,file))==True:
if file.find('.')newname=file+'rsfdjndk.jpg'
os.rename(os.path.join(path,file),os.path.join(path,newname))
print file,'ok'
# print file.split('.')[-1]

实现的方法是:首先遍历path指定的目录,如果是文件(不是文件夹)并且文件名中不存在 ‘.' ,也就是没有后缀名,就把这个文件加上后缀名,然后重命名

有些细节需要注意:

1.如果path指定的文件夹不是这个程序的所在的目录,rename函数里面的路径就必须是绝对路径,否则就会报‘WindowsError: [Error 2]'错误

2.重命名时如果新文件名已经存在,就会报‘WindowsError: [Error 183]' 错误,所以,新文件名最好加上一些随机字符串

3.如果改文件名或者后缀名可以用split() 函数进行分割

4.find函数如果找不到指定的字符串的话就会返回 ‘-1'
博主ma6174
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!