保存下面的代码,以下代码默认(无传参)会遍历文件所在当前目录下的所有子目录和子文件,比如说代码文件名字为main.py,可以把代码放到乱码名字所在目录,执行
python3 main.py
也可以指定路径,比如说要转换的乱码文件或目录在 /home/zhangwei/data/,执行
python3 main.py /home/zhangwei/data/
#!tools
# 437 + 17593 encoding
import os
import sys
def convertOnePath(filePath):
filesInDir = os.listdir(filePath)
needToConvert = []
for file in filesInDir:
try:
nameBinary = bytes(file, "cp437")
for a in nameBinary:
if a > 0x80:
print(file)
needToConvert.append(file)
break
except UnicodeEncodeError as uee:
continue
if len(needToConvert) == 0:
print("None file(s) need to convert")
else:
cvtConfirm = input(
"Convert chinese disorder code file in "+filePath+"? [y/n] : ")
if cvtConfirm != "n" and cvtConfirm != "N" and cvtConfirm != "0":
for file in needToConvert:
newName = bytes(file, "cp437").decode("gb18030")
if not os.path.isfile(filePath+'/'+newName):
os.rename(filePath+'/'+file, filePath+'/'+newName)
if len(sys.argv) > 1:
convertPath = sys.argv[1]
else:
convertPath = os.getcwd()
filePathList = []
filePathList.append(convertPath)
for rootDir, subDir, fileName in os.walk(convertPath):
if (len(subDir) != 0):
for sub in subDir:
filePathList.append(rootDir+'/'+sub+'/')
# from the leaf to the root, otherwise dir names may be changed and cannot traverse
filePathList.sort()
filePathList.reverse()
for filePath in filePathList:
convertOnePath(filePath)