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

如下代码:

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
    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')

即可解决

 

你可能感兴趣的:(Python文件写入时的编码问题解决)