首页 > 解决方案 > 如何将 unicode 写入 txt?Python

问题描述

我想知道如何不仅可以在 txt 文件中写入 ascci 的 128 个字符,还可以写入 unicode 的字符,我想创建文件并开始写入,然后我想重新打开该文件并继续在它下面写入.

考虑到我需要复制文件的内容,也就是说,我应该看不到任何内容,例如a

 \n 

但是换行

依此类推,对于您可以输入的每个 unicode 字符,重点不是让程序读取它,而是拥有 txt 文件并从记事本中安静地读取它

def write_file(text, name_table):
    file = open("llenado_tabla_" + name_table + ".txt","a")
    file.write(text)
    file.close()

def create_file(name_table, atributos):
    file = open("llenado_tabla_" + name_tabla + ".txt","w")
    file.write("-- Llenando tabla " + name_tabla + '\n')
    file.write("INSERT INTO\n")
    file.write(nombre_tabla + '(')
    for i in range(len(atributos)):
        if i == len(atributos) - 1:
            file.write(atributos[i] + ') \n VALUES \n')
        else:
            file.write(atributos[i] + ',')
    file.close()

当我尝试时,我收到此错误:

Traceback (most recent call last):
  File "D:\Projects2.0\4to semestre\Bases de datos\creador_tablas.py", line 96, in <module>
    main()
  File "D:\Projects2.0\4to semestre\Bases de datos\creador_tablas.py", line 95, in main
    introducir_registros(atributos, tipo_dato, cantidad_id, id_generado, nombre_tabla)
  File "D:\Projects2.0\4to semestre\Bases de datos\creador_tablas.py", line 62, in introducir_registros
    insertar_datos_txt(datos_tabla, False, nombre_tabla)
  File "D:\Projects2.0\4to semestre\Bases de datos\creador_tablas.py", line 29, in insertar_datos_txt
    escribe_fichero(texto, nombre_tabla)
  File "D:\Projects2.0\4to semestre\Bases de datos\creador_tablas.py", line 3, in escribe_fichero
    archivo.write(texto)
  File "C:\Python39\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2212' in position 25: character maps to <undefined>

标签: python

解决方案


Python 会透明地为你处理这个问题。Python,尤其是 Python 3,本机使用 unicode 字符。当您将它们写入文件时,它通常以 unicode 文件格式写入。读书也一样

这是一个示例:

data = "3 unicode chars > ☀️‼️ <"

with open('/tmp/data.uni', 'w') as f:
    f.write(data)

with open('/tmp/data.uni') as f:
    read_data = f.read()

print(read_data)

结果:

3 unicode chars > ☀️‼️ <

这有点在 StackOverflow 网站上搞砸了,但在我的 PyCharm 的 Mac 上,我的编辑器和运行程序时的输出中有三个表情符号。

这是它在我的 Mac 上的样子:

我的 Mac 上的表情符号


推荐阅读