重新立名檔案或資料夾


Posted by chenchih on 2021-07-25

今天我想要分享如何用python改檔名或資料夾。我認為這很方便可以給大家參考看看。

檔案立名File Rename 或資料夾

Example1: 找相關檔名再取名,用startswith

檔名: 2020_test_test_test.txt ==>改成 test_test_test.txt

可以用此方式找完整路徑 :
import pathlib
pathlib.Path().resolve()
**目前目錄 :
os.listdir(".")

import os 
for filename in os.listdir("."):
    if filename.startswith("2020"):   
        os.rename(filename, filename[5:])

以上方法是簡單方式,可是有缺點,如果有其他檔名就無法用這樣方式,你可以看到[5:],把5以後改掉。
你也可以用 endswith這個method。

用法:
str.startswith(search_string, start, end)
str.endswith( search_string, start, end)
有興趣可以到 https://www.w3schools.com/python/ref_string_startswith.asp

Example2: 找相關檔名再取名,用dictonary

檔名: (FHD) Test-File [中文字幕].txt ==>改成 Test-File.txt
這方法很不錯,你只想要改個名稱放進去KEY理面。如果你有多檔案在這目錄,會很方便。

import os
for filename in os.listdir("."): 
    if filename.endswith(".txt"):      
        char_to_replace = {'(FHD) ': '', '[中文字幕]': ''}
        filename_old= filename
        for key, value in char_to_replace.items():
            filename = filename.replace(key, value)         
        #print(filename_old)
        #print(filename)
        os.rename(filename_old, filename)

你們也可以用字串String 做測試看看,如果沒問題再用上面方式os.rename這個method。

sample_string = "(FHD) Test-File [中文字幕].txt"
char_to_replace = {'(FHD) ':'','[中文字幕]':''}
for key, value in char_to_replace.items():
    # Replace key character with value character in string
    sample_string = sample_string.replace(key, value)
print(sample_string)

reference:
https://stackoverflow.com/questions/7509221/removing-renaming-files-in-python
https://stackoverflow.com/questions/37467561/renaming-multiple-files-in-a-directory-using-python

資料夾立名 Folder/directory Rename

資料夾也跟檔案一樣都是用rename module。可以慘考這個方式也可以,就是把資料夾的名稱-以前移掉,如下

import os
import pathlib
path = pathlib.Path().resolve()
directory_list = os.listdir(path)
print("List of directory:  ", directory_list )
print("=" *50)
for filename in directory_list:
    src = filename
    dst = filename[filename.find('-') + 1:]
    # print(dst)
    #os.rename(src, dst)
    os.rename(os.path.join(path, src), os.path.join(path, dst))
print("File renamed!")

reference: https://stackoverflow.com/questions/61314529/rename-multiple-folder-in-a-directory-with-python

Notepad++ regular expression

設你想移除網頁後面文字,可以用regualr expression 方式 "*$ "
我只是用很簡單的文字方式,我只到還有更簡單方式,用replace 或反選文字也可以。我只是要用regular expression方式,今天如果你有比較不一樣文字,可以用


reference : https://superuser.com/questions/391318/how-do-i-remove-the-last-part-of-every-line-in-notepad/391324


#Python #rename-file #rename-folder







Related Posts

類別繼承範例

類別繼承範例

forEach 和 for迴圈

forEach 和 for迴圈

IC Design Contest Cell-Based 考古題 分享 及 比賽心得

IC Design Contest Cell-Based 考古題 分享 及 比賽心得


Comments