當(dāng)你在pycharm中運行py文件時原朝,有事會提示你如下錯誤:
image
則說明py文件中有中文注釋智嚷,但是在你py文件最開始處沒有添加# -*- coding: utf-8 -*-
代碼
我們知道如果你該文件夾下py文件很多陵像,如果一個一個文件的添加是很麻煩的琅关,我們可以使用以下代碼舅世,運行完成后凄硼,文件夾下的所有文件的首行都加上了該行代碼孕讳。
import os
line = '# -*- coding: utf-8 -*-'
py_files = [x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1] == '.py']
for filename in py_files:
if filename == 'utf8.py':
continue
with open (filename, 'r') as f:
orig_f = f.read()
if 'utf-8' not in orig_f[0:20]:
new_f = line + '\n' + orig_f
with open (filename, 'w') as f:
f.write(new_f)