1 回答
TA貢獻1848條經驗 獲得超6個贊
至少有五個問題:
處理 Unicode 時,請在任何地方使用它。
os.walk如果傳遞 Unicode 路徑,將返回 Unicode 文件名。from __future__ import unicode_literals將默認字符串為 Unicode。打開文件時,關閉它們。稍后重命名時會遇到問題。
result仍然存在并引用了上次打開的文件。正如評論中提到的,在名稱和名稱之前和之后都使用
os.path.joinonroot和 thefile。os.walk與 一起使用topdown=False。這首先會處理葉節點,所以目錄樹沒有被破壞(并保持root和dirs有效),而穿越它。首先重命名文件,然后重命名目錄,以免在遍歷目錄樹時損壞目錄樹。
結果:
from __future__ import unicode_literals
# Skipping unchanged code...
for root, dirs, files in os.walk('./input_folder'):
for dir in dirs:
# One way to ensure the file is closed.
with open(os.path.join(root,dir) + '/ABC ' + str(random.randint(100,999)) + '.dat','w'):
pass
with open(os.path.join(root,dir) + '/XYZ-ABC ' + str(random.randint(100,999)) + '.dat','w'):
pass
#--------------------------------------
# Main rename code
for root, dirs, files in os.walk('./input_folder',topdown=False):
for file in files:
if file.endswith((".dat")):
# Generate the full file path names.
filename1 = os.path.join(root,file)
filename2 = os.path.join(root,file.replace('ABC', '\u2714'))
os.rename(filename1,filename2)
for d in dirs:
# Generate the full directory path names.
dirname1 = os.path.join(root,d)
dirname2 = os.path.join(root,d.replace('ABC', '\u2714'))
os.rename(dirname1,dirname2)
添加回答
舉報
