Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
特殊字符(é;、ê;,等等)赢得';在Python3.8和xlsxwriter中写入输出时,无法正确显示_Python_Python 3.x_Excel_Text - Fatal编程技术网

特殊字符(é;、ê;,等等)赢得';在Python3.8和xlsxwriter中写入输出时,无法正确显示

特殊字符(é;、ê;,等等)赢得';在Python3.8和xlsxwriter中写入输出时,无法正确显示,python,python-3.x,excel,text,Python,Python 3.x,Excel,Text,我正在使用几个文本文件将输出写入Excel文件。 除了像é、ê等特殊字符的格式之外,一切都很正常 以下是输入文本文件的示例: 请鼓励Nehvandré多大声朗读 以下是将特定文本写入Excel文件的方式: 请鼓励Nehvandré多大声朗读 下面是我用来遍历文本文件并将文件内容写入Excel文件的代码 from pathlib import Path import os import xlsxwriter txt_dir = r"D:\PYTHON_SCRIPTS\****\com

我正在使用几个文本文件将输出写入Excel文件。 除了像é、ê等特殊字符的格式之外,一切都很正常

以下是输入文本文件的示例:

请鼓励Nehvandré多大声朗读

以下是将特定文本写入Excel文件的方式:

请鼓励Nehvandré多大声朗读

下面是我用来遍历文本文件并将文件内容写入Excel文件的代码

from pathlib import Path
import os
import xlsxwriter

txt_dir = r"D:\PYTHON_SCRIPTS\****\comment_output"
subfolder_name = [f.name for f in os.scandir(txt_dir) if f.is_dir()]
subfolder_path = [f.path for f in os.scandir(txt_dir) if f.is_dir()]

sub_index = 0
while sub_index < len(subfolder_name):
    row = 0
    col = 0
    workbook = xlsxwriter.Workbook(subfolder_path[sub_index] + f"\\{subfolder_name[sub_index]}.xlsx")
    worksheet = workbook.add_worksheet()
    for file in Path(subfolder_path[sub_index]).glob("*.txt"):
        with open(file, "r") as txt_file:
            encoded_file = file.read_text()
            worksheet.write(row, col, file.name[:-4])
            worksheet.write(row, col + 1, encoded_file)
            row += 1
        os.remove(file)
    workbook.close()
    sub_index += 1
从pathlib导入路径
导入操作系统
导入xlsxwriter
txt\u dir=r“D:\PYTHON\u脚本\***\comment\u输出”
子文件夹_name=[f.如果f.为_dir(),则在os.scandir(txt_dir)中为f.命名]
子文件夹_-path=[f.是_-dir()时,在os.scandir(txt_-dir)中f的f.path]
次级指数=0
而子文件夹索引
如何使Excel文件中的文本与TXT文件中的文本相同?
我正在使用Python 3.8

Enetrati和jmcnamara的评论为我指明了正确的方向,我在打开文本文件时设置了编码:

 with open(file, encoding="utf-8", mode="r") as txt_file:

更改后,输出完全符合预期。

Enetrati和jmcnamara的评论为我指出了正确的方向,我在打开文本文件时设置了编码:

 with open(file, encoding="utf-8", mode="r") as txt_file:

在这一更改之后,输出完全符合预期。

您肯定应该看看Unicode。这(以及下面的示例)可能是文档中更好的示例,因为它涉及到读取文本文件:感谢您为我指明了正确的方向,我偶然发现了另一种在打开文件时选择正确编码的方法:使用open(file,encoding=“utf-8”,mode=“r”)正如txt_文件:这就成功了。你一定要看看Unicode。这(以及下面的示例)可能是文档中一个更好的例子,因为它处理文本文件的读取:感谢您为我指明了正确的方向,我偶然发现了另一种在打开文件时选择正确编码的方法:使用open(file,encoding=“utf-8”,mode=“r”)作为txt\u文件:这就成功了。