【Python开发】python重命名文件和遍历文件夹操作

来源:互联网 发布:淘宝买家秀怎么发布 编辑:程序博客网 时间:2024/06/14 09:36

当前文件夹下,把所有文件名中的“50076“替换成”50092“,用Python实现,代码所下:


# encoding: utf-8  import os  import os.path    curDir = os.getcwd()  oldId = "50076"  newId = "50092"  for parent, dirnames, filenames in os.walk(curDir):        for filename in filenames:          if filename.find(oldId)!=-1:              newName = filename.replace(oldId, newId)              print(filename, "---->", newName)              os.rename(os.path.join(parent, filename), os.path.join(parent, newName))    os.system("pause")



附:遍历特定文件夹中的文件以及子文件夹,代码如下:


# encoding: utf-8  import os  import os.path  rootdir = r'D:\game'    # 指明被遍历的文件夹    #三个参数:分别返回1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字  for parent, dirnames, filenames in os.walk(rootdir):          for dirname in dirnames:    #输出文件夹信息          print "parent is: " + parent          print "dirname is: " + dirname        for filename in filenames:  #输出文件信息          print "parent is: " + parent          print "filename is: " + filename          print "the full name of the file is: " + os.path.join(parent,filename) #输出文件路径信息  


0 0
原创粉丝点击