python檔案怎麼重新命名 python檔案重新命名

2021-10-19 21:35:31 字數 1083 閱讀 7744

當前資料夾下,把所有檔名中的「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) #輸出檔案路徑資訊

python 檔案重新命名

獲取資料夾路徑 def get dirs dir dirlist for root,dirs,files in os.walk dir for d in dirs dirlist.os.path.join root,d return dirlist 獲取檔案的路徑 def get files dir...

Python遍歷檔案,重新命名

import os.path rootdir input enter your input i 0 for parent,dirnames,filenames in os.walk rootdir for filename in filenames print parent is parent pr...

python實現檔案重新命名

encoding utf 8 importos path demo1 filelist os.listdir path 該資料夾下所有的檔案 包括資料夾 count 0 forfileinfilelist print file forfileinfilelist 遍歷所有檔案 olddir os.p...