Python 文件重命名工具代码

yipeiwu_com5年前Python基础
复制代码 代码如下:

#Filename:brn.py
#Description: batch replace certain words in file names
#Use to bat rename the file in a dir(modify the suffix from a to b) for Windows Vista OS
import sys
import os
import fnmatch
import re
#parse params
p=input("Please input work directory(current path for enter):")
if p=='\r':
p='.'
p=p.rstrip('\r')
print (p)
while not os.path.exists(p):
print (p+' is not existed.Please input the work directory:')
p=input("Please input work directory(current path for enter):")
s=input("Please enter the words which need be modified(must):")
while s=='\r':
s=input("Please enter the words which need be replaced(must):")
s=s.rstrip('\r')
d=input("Please enter the words which want to change to(must):")
while d=='\r':
d=input("Please enter the words which want to change to(must):")
d=d.rstrip('\r')
try:
sure=input("Are you sure to rename the file named *"+s+"*"+" to *"+d+"*"+" in directory "+p+"? y/n:")
sure=sure.rstrip('\r')
if sure!='y':
print ("Cancel")
else:
for root, dirs, files in os.walk(p, True):
for file in files:
print (os.path.join(root,file))
if os.path.isfile(os.path.join(root,file)):#Only file is file,not a dir ,do this
if fnmatch.fnmatch(file, '*'+s+'*'):
f=str(file).replace(s,d)
if p=='.':
command='move '+str(file)+" "+f
else:
command="move "+os.path.join(root,file)+" "+os.path.join(root,f)
print (command)
if os.system(command)==0:#do actual rename
print ("Rename "+str(file)+" to "+f+" success")
else:
print ("Rename "+str(file)+" to "+f+" failed")
#else:
#print str(file)+" is a directory.omit"
except IndexError:
print (IndexError.message)

相关文章

Python编程中对super函数的正确理解和用法解析

当在子类需要调用父类的方法时,在python2.2之前,直接用类名调用类的方法,即非绑定的类方法,并把自身对象self作参数传进去。 class A(object): def...

python找出因数与质因数的方法

最近有一个学弟问我一些求解质因数的问题,帮他解决问题的同时自己也试着写了几个差不多效果的脚本,有很多不同的思路,以下是相关脚本。 n = int(input("input numbe...

使用Tensorflow将自己的数据分割成batch训练实例

使用Tensorflow将自己的数据分割成batch训练实例

学习神经网络的时候,网上的数据集已经分割成了batch,训练的时候直接使用batch.next()就可以获取batch,但是有的时候需要使用自己的数据集,然而自己的数据集不是batch形...

pytorch 指定gpu训练与多gpu并行训练示例

一. 指定一个gpu训练的两种方法: 1.代码中指定 import torch torch.cuda.set_device(id) 2.终端中指定 CUDA_VISIBLE_DEV...

Python配置文件处理的方法教程

Python配置文件处理的方法教程

前言 在平时的工程中,我们在构建工程时,常常需要用到配置文件,用来配置项目的一些信息,比如数据库,请求网址,文件夹,线程、进程数等信息,这样就可以方便我们通过修改配置文件中的参数来很好地...