Skip to content

Instantly share code, notes, and snippets.

@david4958606
Created April 16, 2023 10:22
Show Gist options
  • Save david4958606/ee160c39e483379d6b3f408ce6c011bd to your computer and use it in GitHub Desktop.
Save david4958606/ee160c39e483379d6b3f408ce6c011bd to your computer and use it in GitHub Desktop.
import os
import sys
import chardet
def get_encoding(file):
with open(file, 'rb') as f:
return chardet.detect(f.read())['encoding']
print(get_encoding("name_list.txt"))
if get_encoding("name_list.txt") == "utf-8" or get_encoding("name_list.txt") == "UTF-8-SIG" or get_encoding("name_list.txt") == "Windows-1252" or get_encoding("name_list.txt") == "ascii": # 可能的兼容utf-8的编码
if get_encoding("name_list.txt") == "UTF-8-SIG":
print("检测到 UTF-8-SIG 编码,尝试转换为 UTF-8")
# convert utf-8-sig to utf-8
with open("name_list.txt", "rb") as f:
data = f.read()
data = data.replace(b'\xef\xbb\xbf', b'')
with open("name_list.txt", "wb") as f:
f.write(data)
print(get_encoding("name_list.txt"))
if get_encoding("name_list.txt") == "uft-8" or get_encoding("name_list.txt") == "Windows-1252" or get_encoding("name_list.txt") == "ascii":
print("转换成功")
else:
raise Exception("转换失败")
else:
raise Exception("检测到非 UTF-8 编码,请检查文件编码")
file_list = sys.argv[1:]
list = open("name_list.txt", "r+")
names = list.readlines()
list.close()
if len(file_list) != len(names):
raise ValueError("定义文件名条目数与实际文件数不符!")
i = 0
for line in names:
line = line.strip() # 去除文件名前后空格
print(line)
file = file_list[i]
i += 1
(path, name) = os.path.split(file) # 获取路径和文件名
os.chdir(path)
(pname, ext) = os.path.splitext(name) # 获取文件名和拓展名
if pname == line:
print("文件名未改变")
continue
dst = line + ext # 给目标文件名加上拓展名
os.rename(file, dst)
print(dst)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment