起因:大三做日本交换生期间在修一门C语言图像处理的编程课,在配套书籍的网站上下载了sample,但是由于我用的ubuntu18.04系统默认用utf-8编码,而文件源码是Shift_JIS编码,因而文档注释是乱码。在不改变系统默认编码的前提下,用python将’.c’和’.h’文件的编码转换保存新的文件夹,其余文件原封不动复制。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
701 import os 2 3 abspath = "/home/fanghaoyu/桌面/libraries/" # 新文件夹的路径 4 try: 5 os.makedirs(abspath) # 创建新文件夹 6 except FileExistsError: 7 pass 8 a = [] # 定义列表a,用来存放原文件的路径 9 b = [] # 定义列表b,用来存放新文件的路径 10 11 12 # 函数用来递归获取文件,更改编码写入到新文件夹中,如果不是.c和.h文件则复制 13 def get_file_name(path1, path2): 14 for i in os.listdir(path1): 15 if os.path.isdir(os.path.join(path1, i)): 16 try: 17 os.makedirs(os.path.join(path2, i)) 18 except FileExistsError: 19 pass 20 get_file_name(os.path.join(path1, i), os.path.join(path2, i)) 21 else: 22 a.append(os.path.join(path1, i)) 23 b.append(os.path.join(path2, i)) 24 if a[-1].endswith('.c') or a[-1].endswith('.h'): 25 with open(a[-1], 'r', encoding='Shift_JIS') as fp: 26 s = fp.read() 27 with open(b[-1], 'w') as fp2: 28 fp2.write(s) 29 fp2.close() 30 else: 31 a[-1] = a[-1].replace(' ', ' ').replace('(', '(').replace(')', ')') 32 b[-1] = b[-1].replace(' ', ' ').replace('(', '(').replace(')', ')') 33 os.system('cp {} {}'.format(a[-1].strip('''), b[-1].strip('''))) 34 35 return 0 36 37 38 get_file_name("/home/fanghaoyu/桌面/prog978-4-7856-3179-6/", abspath) 39 print(a) 40 print(len(a)) 41 print(b) 42 print(len(b))
运行结果如下:
复制代码
1
2
3
4
5
6
7/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 Process finished with exit code 0
需要注意的几点:
open打开原文件,打开方式用’r’,则需要设置编码方式encoding=‘Shift_JIS’
python的os.system()命令中调用ubuntu的shell命令,当cp的文件名中含有’ ', ‘(’, ‘)‘这三个时,需要在前面加上反斜杠’’,否则会报错
最后多说一句,小编是一名python开发工程师,这里有我自己整理了一套最新的python系统学习教程,包括从基础的python脚本到web开发、爬虫、数据分析、数据可视化、机器学习等。想要这些资料的可以关注小编,并在后台私信小编:“01”即可领取。
最后
以上就是爱笑煎蛋最近收集整理的关于python实现文件批量编码转换的全部内容,更多相关python实现文件批量编码转换内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复