我在目录中有4个文件(具有不同的扩展名),如下所示。
Test1234_`enter code here`Dir (Directory)
FileA_1234_test.dat
FileAAB_1234_test.log
FileABCD_1234_test.dbm
FileABCDE_1234_test.jdt
I want to replace part of directory and file names as shown below
Test6789_Dir (Directory)
FileA_6789_test.dat
FileAAB_6789_test.log
FileABCD_6789_test.dbm
FileABCDE_6789_test.jdt
我们如何在Python3中实现这一目标?我不知道这样做。
答案 0 :(得分:0)
我不确定你想做什么。 也许是这样的
def replace_names(path, str_to_replace='1234', replacement='6789'):
import os
for filename in os.listdir(first_path):
if '_'+str_to_replace+'_' in filename:
new_filename = filename.replace(str_to_replace, replacement)
os.rename(filename, new_filename )
os.rename(path, .replace(str_to_replace, replacement))
#now, run it...
replace_names('Test1234_Dir')