博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Python文件写入时的编码问题解决

Posted on 2018-08-23 19:08  Yonguos  阅读(738)  评论(0编辑  收藏  举报

如下代码:

import sys
import os

import django

root_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
sys.path.append(root_dir)
os.environ['DJANGO_SETTINGS_MODULE'] = 'jumpserver.settings'
django.setup()

from juser.models import User

all_user = User.objects.all()

with open("/root/csm_user.txt", "w") as f:
    for user in all_user:
        data = "{username} {name} \n".format(username=user.username, name=user.name)
        print(data)
        f.write(data)

直接运行会报错:

Traceback (most recent call last):
  File "/opt/data/workspace/CloudSecureMgmt0731/juser/dd.py", line 20, in <module>
    data = "{username} {name} \n".format(username=user.username, name=user.name)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

重新加载设置编码:

import sys
reload(sys) 
sys.setdefaultencoding('utf-8')

即可解决