简体   繁体   English

Python:无法写入文件-UnicodeEncodeError

[英]Python: Can't write to file - UnicodeEncodeError

This code should write some text to file. 此代码应将一些文本写入文件。 When I'm trying to write my text to console, everything works. 当我尝试将文本写入控制台时,一切正常。 But when I try to write the text into the file, I get UnicodeEncodeError. 但是,当我尝试将文本写入文件时,出现UnicodeEncodeError。 I know, that this is a common problem which can be solved using proper decode or encode, but I tried it and still getting the same UnicodeEncodeError. 我知道,这是一个常见问题,可以使用正确的解码或编码来解决,但是我尝试了一下,仍然得到了相同的UnicodeEncodeError。 What am I doing wrong? 我究竟做错了什么?

I've attached an example. 我附了一个例子。

print "(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)".decode("utf-8")%(dict.get('name'),dict.get('description'),dict.get('ico'),dict.get('city'),dict.get('ulCislo'),dict.get('psc'),dict.get('weby'),dict.get('telefony'),dict.get('mobily'),dict.get('faxy'),dict.get('emaily'),dict.get('dic'),dict.get('ic_dph'),dict.get('kategorie')[0],dict.get('kategorie')[1],dict.get('kategorie')[2])

(StarBuy sro,Inzertujte s foto, auto-moto, oblečenie, reality, prácu, zvieratá, starožitnosti, dovolenky, nábytok, všetko pre deti, obuv, stroj.... (StarBuy sro,Inzertujte s摄影,汽车,oblečenie,现实,prácu,zvieratá,starožitnosti,dovolenky,nábytok,všetkopre deti,obuv,stroj ....

with open("test.txt","wb") as f:
   f.write("(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)".decode("utf-8")%(dict.get('name'),dict.get('description'),dict.get('ico'),dict.get('city'),dict.get('ulCislo'),dict.get('psc'),dict.get('weby'),dict.get('telefony'),dict.get('mobily'),dict.get('faxy'),dict.get('emaily'),dict.get('dic'),dict.get('ic_dph'),dict.get('kategorie')[0],dict.get('kategorie')[1],dict.get('kategorie')[2]))

UnicodeEncodeError: 'ascii' codec can't encode character u'\č' in position 50: ordinal not in range(128) UnicodeEncodeError:'ascii'编解码器无法在位置50编码字符u'\\ u010d':序数不在范围内(128)

Where could be the problem? 问题可能出在哪里?

To write Unicode text to a file, you could use io.open() function : 要将Unicode文本写入文件,可以使用io.open()函数

#!/usr/bin/env python
from io import open

with open('utf8.txt', 'w', encoding='utf-8') as file:
    file.write(u'\u010d')

It is default on Python 3. 在Python 3上是默认设置。

Note: you should not use the binary file mode ( 'b' ) if you want to write text. 注意:如果要编写文本,则不应使用二进制文件模式( 'b' )。

# coding: utf8 that defines the source code encoding has nothing to do with it. # coding: utf8定义源代码编码的# coding: utf8与它无关。

If you see sys.setdefaultencoding() outside of site.py or Python tests; 如果您在site.py或Python测试之外看到sys.setdefaultencoding() assume the code is broken. 假设代码已损坏。

@ned-batchelder is right. @ ned-batchelder是正确的。 You have to declare that the system default encoding is "utf-8". 您必须声明系统默认编码为“ utf-8”。 The coding comment # -*- coding: utf-8 -*- doesn't do this. 编码注释# -*- coding: utf-8 -*-不这样做。

To declare the system default encoding, you have to import the module sys , and call sys.setdefaultencoding('utf-8') . 要声明系统默认编码,您必须导入模块sys ,然后调用sys.setdefaultencoding('utf-8') However, sys was previously imported by the system and its setdefaultencoding method was removed. 但是, sys以前是由系统导入的,并且删除了它的setdefaultencoding方法。 So you have to reload it before you call the method. 因此,您必须在调用该方法之前重新加载它。

So, you will need to add the following codes at the beginning: 因此,您将需要在开始时添加以下代码:

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

You may need to explicitly declare that python use UTF-8 encoding. 您可能需要明确声明python使用UTF-8编码。

The answer to this SO question explains how to do that: Declaring Encoding in Python 这样的问题的答案解释了如何做到这一点: 在Python中声明编码

For Python 2: 对于Python 2:

  1. Declare document encoding on top of the file (if not done yet): 在文件顶部声明文档编码(如果尚未完成):

    # -*- coding: utf-8 -*-

  2. Replace .decode with .encode : .decode替换为.encode

     with open("test.txt","wb") as f: f.write("(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)".encode("utf-8")%(dict.get('name'),dict.get('description'),dict.get('ico'),dict.get('city'),dict.get('ulCislo'),dict.get('psc'),dict.get('weby'),dict.get('telefony'),dict.get('mobily'),dict.get('faxy'),dict.get('emaily'),dict.get('dic'),dict.get('ic_dph'),dict.get('kategorie')[0],dict.get('kategorie')[1],dict.get('kategorie')[2])) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试加密和写入文件时Python中的UnicodeEncodeError - UnicodeEncodeError in Python when trying to encrypt and write to a file Python3 f.write UnicodeEncodeError: 'utf-8' codec can't encode characters surrogates 不允许 - Python3 f.write UnicodeEncodeError: 'utf-8' codec can't encode characters surrogates not allowed Python无法解码网站UnicodeEncodeError - Python can't decode website UnicodeEncodeError 试图在Python中将变量写入文件,但出现UnicodeEncodeError - Trying to write a variable to a file in Python, and I get UnicodeEncodeError Python 3-UnicodeEncodeError:“ charmap”编解码器无法编码字符(编码后在文件中) - python 3 - UnicodeEncodeError: 'charmap' codec can't encode character (Encode so it's in a file) Python 3: os.walk() 文件路径 UnicodeEncodeError: 'utf-8' codec can't encode: surrogates not allowed - Python 3: os.walk() file paths UnicodeEncodeError: 'utf-8' codec can't encode: surrogates not allowed 将结果从 python 写入 csv 文件 [UnicodeEncodeError: 'charmap' codec can't encode character - Writing out results from python to csv file [UnicodeEncodeError: 'charmap' codec can't encode character Python 文件无法写入 - Python File Can't Write Python:UnicodeEncodeError:'latin-1'编解码器无法对字符进行编码 - Python: UnicodeEncodeError: 'latin-1' codec can't encode characters in position Python:UnicodeEncodeError:'latin-1'编解码器不能编码字符 - Python : UnicodeEncodeError: 'latin-1' codec can't encode character
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM