importos
abspath="/home/fanghaoyu/桌面/libraries/"#新文件夹的路径
try:
os.makedirs(abspath)#创建新文件夹
exceptFileExistsError:
pass
a=[]#定义列表a,用来存放原文件的路径
b=[]#定义列表b,用来存放新文件的路径
#函数用来递归获取文件,更改编码写入到新文件夹中,如果不是.c和.h文件则复制
defget_file_name(path1,path2):
foriinos.listdir(path1):
ifos.path.isdir(os.path.join(path1,i)):
try:
os.makedirs(os.path.join(path2,i))
exceptFileExistsError:
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))
ifa[-1].endswith('.c')ora[-1].endswith('.h'):
withopen(a[-1],'r',encoding='Shift_JIS')asfp:
s=fp.read()
withopen(b[-1],'w')asfp2:
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('\'')))
return0
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',...]
1970
['/home/fanghaoyu/桌面/libraries/chap06/vq.c','/home/fanghaoyu/桌面/libraries/chap06/vqcode.c',...]
1970
Processfinishedwithexitcode0

需要注意的几点:

open打开原文件,打开方式用'r',则需要设置编码方式encoding='Shift_JIS'

python的os.system()命令中调用ubuntu的shell命令,当cp的文件名中含有'', '(', ')'这三个时,需要在前面加上反斜杠'\',否则会报错

总结

以上所述是小编给大家介绍的python实现文件批量编码转换及注意事项,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

热门推荐

1 要红包拜年祝福语简短
2 l离别祝福语大全简短
3 新年祝福语简短叔叔阿姨
4 谷雨祝福语简短文字
5 长辈祝福语简短小故事
6 公司年会祝福语简短感谢
7 老公生日祝福语简短情话
8 女儿升大班祝福语简短
9 送企业祝福语简短的
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短