码农公社 210.net.cn 210= 1024 10月24日一个重要的节日--码农(程序员)节
在不改变系统默认编码的前提下,用python将某些扩展名的文件的编码转换保存到新的文件夹以消除乱码等问题,其余文件原封不动复制。
import os
abspath = "/home/fanghaoyu/桌面/libraries/" # 新文件夹的路径
try:
os.makedirs(abspath) # 创建新文件夹
except FileExistsError:
pass
a = [] # 定义列表a,用来存放原文件的路径
b = [] # 定义列表b,用来存放新文件的路径
# 函数用来递归获取文件,更改编码写入到新文件夹中,如果不是.c和.h文件则复制
def get_file_name(path1, path2):
for i in os.listdir(path1):
if os.path.isdir(os.path.join(path1, i)):
try:
os.makedirs(os.path.join(path2, i))
except FileExistsError:
pass
get_file_name(os.path.join(path1, i), os.path.join(path2, i))
else:
a.append(os.path.join(path1, i))
b.append(os.path.join(path2, i))
if a[-1].endswith('.c') or a[-1].endswith('.h'):
with open(a[-1], 'r', encoding='Shift_JIS') as fp:
s = fp.read()
with open(b[-1], 'w') as fp2:
fp2.write(s)
fp2.close()
else:
a[-1] = a[-1].replace(' ', '\ ').replace('(', '\(').replace(')', '\)')
b[-1] = b[-1].replace(' ', '\ ').replace('(', '\(').replace(')', '\)')
os.system('cp {} {}'.format(a[-1].strip('\''), b[-1].strip('\'')))
return 0
get_file_name("/home/fanghaoyu/桌面/prog978-4-7856-3179-6/", abspath)
print(a)
print(len(a))
print(b)
print(len(b))
运行结果如下:
/usr/bin/python3.6 /home/fanghaoyu/桌面/python/coding_change.py
['/home/fanghaoyu/桌面/prog978-4-7856-3179-6/chap06/vq.c', '/home/fanghaoyu/桌面/prog978-4-7856-3179-6/chap06/vqcode.c',...]
['/home/fanghaoyu/桌面/libraries/chap06/vq.c', '/home/fanghaoyu/桌面/libraries/chap06/vqcode.c', ...]
Process finished with exit code 0
需要注意的几点:
open打开原文件,打开方式用'r',则需要设置编码方式encoding='Shift_JIS' python的os.system()命令中调用ubuntu的shell命令,当cp的文件名中含有' ', '(', ')'这三个时,需要在前面加上反斜杠'\',否则会报错