解决linux下中文文件名乱码问题
2017-08-25 / Server / 1890 次围观 / 0 次吐槽 /前一段时间将网站迁移到别的主机后,发现很多TXT文件都无法调用和下载。
登录到主机看了下发现文件名了都乱码了,我的TXT文件名是中文命名的,查阅资料后原来是我的文件名
中文是GBK编码的所以在Linux下压缩的时候 自动以UTF-8编码压缩了,所以出现了乱码的现象。
找到了问题就好办的多了,编写一个Python脚本批量转换下编码。
Python
#!/usr/bin/env python
#coding= utf-8
#by Cheug blog:www.cheug.com
import os
import sys
def VisitDir(path):
li = os.listdir(path)
for p in li:
pathname = os.path.join(path,p)
if not os.path.isfile(pathname):
VisitDir(pathname)
else:
if os.path.splitext(p)[1] == '.txt':
try:
filename = p.decode('utf-8').encode('gbk')
#filename = p.decode('utf-8').encode('latin1')
os.rename(pathname,os.path.join(path,filename))
print filename,'OK'
except UnicodeDecodeError:
print pathname
except UnicodeEncodeError:
print pathname
def main():
path = r"/www/wwwroot/"
VisitDir(path)
if __name__ == '__main__':
main()
Powered By Cheug's Blog
Copyright Cheug Rights Reserved.