代码
'''
给py文件第一行加入UTF8编码(如果第一行已设置,则忽略)
'''
import os
def head_set_utf8(dir_path):
for curr, dirs, files in os.walk(dir_path):
for file in files:
if not file.endswith(".py"):
continue
fpath = os.path.join(curr, file)
update_file(fpath)
def update_file(file_path):
with open(file_path, 'r+', encoding="UTF8") as f:
content = f.read()
first_line = content.split("\n")[0]
if first_line.find('utf') != -1 and first_line.find('8') != -1:
return
else:
f.seek(0, 0)
f.write("# -*- coding: utf-8 -*-\n\r" + content)
print("成功 >> {}".format(file_path))
def run(dir_path=None):
dir_path = dir_path if dir_path else os.getcwd()
if not os.path.exists(dir_path):
print('警告 >> 路径不存在 >> {}'.format(dir_path))
return
head_set_utf8(dir_path)
if __name__ == '__main__':
run()