簡體   English   中英

Python改變文件名的一部分

[英]Python changing part of a file name

嗨我有許多不同的文件需要重命名為其他文件。 我得到了這個,但我想擁有它,以便我可以有許多項目來替換和相應的替換而不是輸入每一個,運行代碼然后再次重新鍵入它。 此外,我需要重命名只更改文件的一部分而不是整個文件,所以如果有“Cat5e_1mBend1bottom50m2mBend2top-Aqeoiu31”,它只會將其更改為“'Cat5e50m1mBED_50m2mBE2U-Aqeoiu31運行python 2.5

import os, glob

name_map = {
     "Cat5e_1mBend1bottom50m2mBend2top": 'Cat5e50m1mBED_50m2mBE2U'
}

#searches for roots, directory and files
for root,dirs,files in os.walk(r"H:\My Documents\CrossTalk"):
   for f in files:
       if f in name_map:
          try:
             os.rename(os.path.join(root, f), os.path.join(root, name_map[f]))
          except FileNotFoundError, e:
          #except FileNotFoundError as e:  # python 3
             print(str(e))

正如Hector所指出的,完成此任務的最簡單方法是使用正則表達式。 幸運的是,Python有一個很好的正則表達式模塊,叫做re 基本上我們希望看看我們在name_map中指定的任何模式name_map與我們正在查看的當前文件name_map匹配。 如果模式匹配,則只匹配匹配的部分,然后重命名。

import os, glob, re

name_map = {
    "bad": "good",
    "cat": "dog"
}

for root, dirs, files in os.walk(r"/Users/.../start/"):
    for f in files:
        for name in name_map.keys():
            if re.search(name,f) != None:
                new_name = re.sub(name,name_map[name],f)
                try:
                    os.rename(os.path.join(root,f), os.path.join(root, new_name))
                except OSError:
                    print "No such file or directory!"

因此給定一些目錄以內容startbad_name.txt catdogcat.csv

這將腳本重命名為: good_name.txt dogdogdog.csv

這個的兩個主要內容應該是如何使用re.search()re.sub()方法。 re.search(pattern, string)在提供的字符串中查找模式。 如果找到它,它將返回一個Match對象,如果沒有,那么它將返回None 這使得測試字符串中的模式變得輕而易舉。 一旦我們發現模式存在,下一步就是用我們的新名稱替換它。 輸入re.sub()方法。 re.sub(pattern, replace, string)在提供的字符串中搜索模式,然后用replace的內容替換該模式。

我強烈建議您查看re模塊的文檔,因為它非常強大,可以用來解決許多問題。

那樣的東西?

files = ['something', 'nothing', 'no_really_not',
         'something_something', 'nothing_to_replace']
name_map = {'nothing': 'something',
            'something': 'nothing'}

for f in files:
    for pat, rep  in name_map.iteritems():
        if f.find(pat) >= 0:
            f_new = f.replace(pat, rep)
            print('Rename {} -> {}'.format(f, f_new))
            break
    else:
        print('Keep {}'.format(f))

這是非常行人。 如果應該尊重一個文件的多個替換,那就不好了......

你一定要看看正則表達式

如果你有一個模式定義你需要更改和更換,使用re.sub非常簡單

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM