尝试在Python中打开txt文件时出错

问题描述 投票:0回答:1

我正在使用 Custom Tkinter 制作一个应用程序,在这个应用程序中,我想基于文件夹中的 .txt 文件创建按钮,并使按钮复制这些 .txt 文件的内容。简单的复制/粘贴按钮。

这个按钮类在我的 Mac 上运行得很好,但现在在 Windows 上它给了我错误。

我检查了多次讨论,但没有运气。例如尝试“encoding =“utf-8””,但没有成功。

`类 CopyPaste(customtkinter.CTkScrollableFrame):

def __init__(self, master):
    super().__init__(master)

    global counter
    counter = 1

    self.Header = customtkinter.CTkLabel(self, text="Template Answers",
                                         font=("Arial", 20))
    self.Header.grid(row=0, column=0, padx=10, pady=10, sticky="w")

    target_directory = "C:/ToolKit Files"

    def read_file(file_path):
        with open(file_path, "r") as file:
            content = file.read()
        return content

    def create_button(self, file_path):

        file_name = os.path.basename(file_path)

        def on_button_click():
            pyperclip.copy(read_file(file_path))

        button = customtkinter.CTkButton(self, text=file_name, command=on_button_click)
        button.grid(row=counter, column=0, padx=10, pady=5)

    def create_buttons(self, target_directory):

        file_names = [file for file in os.listdir(target_directory) if file.endswith('.txt')]
        for file_name in file_names:
            global counter
            file_path = os.path.join(target_directory, file_name)
            create_button(self, file_path)
            counter += 1

    create_buttons(self, target_directory)`

运行此脚本后,我收到:

Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__ return self.func(*args) File "C:\Users\USER\PycharmProjects\SidekickToolKit\venv\lib\site-packages\customtkinter\windows\widgets\ctk_button.py", line 554, in _clicked self._command() File "C:\Users\USER\PycharmProjects\SidekickToolKit\main.py", line 162, in on_button_click pyperclip.copy(read_file(file_path)) File "C:\Users\USER\PycharmProjects\SidekickToolKit\main.py", line 154, in read_file content = file.read() File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 448: character maps to <undefined>

非常感谢您的帮助:D

python-3.x customtkinter pyperclip
1个回答
0
投票

您的代码看起来不错,我认为还需要做什么来触发错误,UnicodeDecodeError

traceback is for you to tell Python the
encoding` 用于读取文件。

这是您的代码的更新:


def read_file(file_path):
       # wrap the entire code snippet in a try-catch block
       try:
           with open(file_path, "r", encoding="utf-8") as file:
               content = file.read()
           return content
      # catch the error if any
       except UnicodeDecodeError:
           return f'Error reading file {file}.'

我相信您的代码现在应该可以工作,因为您已将编码设置为

utf-8
。祝你好运,伙计。

© www.soinside.com 2019 - 2024. All rights reserved.