Skip to content

Instantly share code, notes, and snippets.

@potass13
Created June 17, 2023 01:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save potass13/3f319ca84621cc5084cbd9ccb62bfb41 to your computer and use it in GitHub Desktop.
Save potass13/3f319ca84621cc5084cbd9ccb62bfb41 to your computer and use it in GitHub Desktop.
# ファイル名を一括置換する
import os
import glob
def get_file_name_list(files, path):
return [s.replace(path[:-1], '').replace('/', '').replace('\\' , '') for s in files]
before_word = '東京'
after_word = 'tokyo'
dir_path = 'C:/Users/potass/' # ファイルのあるディレクトリ名
print('--- 置換処理前 ---')
files = glob.glob(dir_path + '*' + before_word + '*') # 変更前のキーワードを持つファイル
files1 = glob.glob(dir_path + '*' + after_word + '*') # 変更後のキーワードを持つファイル
print('置換対象ファイル:', get_file_name_list(files, dir_path))
print('置換後のキーワードを持つファイル:', get_file_name_list(files1, dir_path))
# 変更前のキーワードを持つファイルを置換
for file in files:
rename_file = file.replace(before_word, after_word)
os.rename(file, rename_file)
print('--- 置換処理後 ---')
files = glob.glob(dir_path + '*' + before_word + '*') # 変更前のキーワードを持つファイル
files1 = glob.glob(dir_path + '*' + after_word + '*') # 変更後のキーワードを持つファイル
print('置換対象ファイル:', get_file_name_list(files, dir_path))
print('置換後のキーワードを持つファイル:', get_file_name_list(files1, dir_path))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment