亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何為所有文件和相關文件夾重命名/替換帶有 unicode 字符的特定關鍵字?

如何為所有文件和相關文件夾重命名/替換帶有 unicode 字符的特定關鍵字?

慕絲7291255 2021-10-12 17:46:00
我在目錄 ( 'input_folder') 中有以下文件和子目錄,我想更改所有帶有'.dat'擴展名的文件的名稱以及所有具有特定關鍵字 (例如ABC) 和 Unicode 字符的文件夾的名稱。下面給出了一個 MWE:import osimport randomimport errno    #--------------------------------------# Create random folders and files# tzot's forced directory create hack https://stackoverflow.com/a/600612/4576447def mkdir_p(path):    try:        os.makedirs(path)    except OSError as exc:  # Python >2.5        if exc.errno == errno.EEXIST and os.path.isdir(path):            pass        else:            raiseif not os.path.isdir('./input_folder'):    os.makedirs('input_folder')for i in range(10):    mkdir_p('./input_folder/folder_ABC_' + str(random.randint(100,999)))for root, dirs, files in os.walk('./input_folder'):    for dir in dirs:        result = open(os.path.join(root,dir) + '/ABC ' + str(random.randint(100,999)) + '.dat','w')        result = open(os.path.join(root,dir) + '/XYZ-ABC ' + str(random.randint(100,999)) + '.dat','w')#--------------------------------------# Main rename codefor root, dirs, files in os.walk('./input_folder'):    for file in files:          if file.endswith((".dat")):            os.rename(file, file.replace('ABC', u'\u2714'.encode('utf-8')))這個 MWE 給出了以下錯誤:os.rename(file, file.replace('ABC', u'\u2714'.encode('utf-8')))WindowsError: [Error 2] The system cannot find the file specified如何在 Python 2.7 中使用 unioode 字符正確重命名所有具有 ABC 的文件和文件夾?
查看完整描述

1 回答

?
慕勒3428872

TA貢獻1848條經驗 獲得超6個贊

至少有五個問題:

  1. 處理 Unicode 時,請在任何地方使用它。 os.walk如果傳遞 Unicode 路徑,將返回 Unicode 文件名。 from __future__ import unicode_literals將默認字符串為 Unicode。

  2. 打開文件時,關閉它們。稍后重命名時會遇到問題。 result仍然存在并引用了上次打開的文件。

  3. 正如評論中提到的,在名稱和名稱之前和之后都使用os.path.joinonroot和 the file

  4. os.walk與 一起使用topdown=False。這首先會處理葉節點,所以目錄樹沒有被破壞(并保持rootdirs有效),而穿越它。

  5. 首先重命名文件,然后重命名目錄,以免在遍歷目錄樹時損壞目錄樹。

結果:

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)


查看完整回答
反對 回復 2021-10-12
  • 1 回答
  • 0 關注
  • 201 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號