python对文件进行逆序重命名

查考自:http://www.3lian.com/edu/2013/12-26/118871.html


Python批量重命名文件方法很简单我们会利用listdir与rename 再加上目录遍历即可实现文件重命令了,下面整理了一些方法。

  用到了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

#-*- encoding: utf-8 -*-

import os
import re

path = 'd:/verefoster'
#path = os.getcwd()	#获取当前路径
print path	#打印文件路径

count = 0
for i in os.listdir(path):
	count += 1
	
print count		#打印文件数目

for fname in os.listdir(path):
	newfname = fname[-4:]
	newfpath = "%s/%02d%s" % (path,count,newfname)
	count -= 1
	oldfpath = "%s/%s" % (path, fname)
	#对文件进行重命名
	#os.rename(oldfpath, newfpath)
	print oldfpath
	print newfpath



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值