鱼C论坛

 找回密码
 立即注册
查看: 329|回复: 3

读取txt文件转为excel文件报错

[复制链接]
发表于 2024-11-4 10:33:03 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
写了一个代码把txt转为excel,失败了,代码如下
  1. """

  2. 代码如下:

  3. ```python
  4. """
  5. import pandas as pd
  6. import tkinter as tk
  7. from tkinter import filedialog
  8. from tkinter import ttk
  9. import time
  10. from openpyxl import load_workbook
  11. input_file_path = ""
  12. tem_file_path = ""
  13. tar_folder_path = ""
  14. df_merge = []

  15. def select_input_file():
  16.     global input_file_path
  17.     input_file_path = filedialog.askopenfilename(filetypes=[("text files", "*.txt")], title="请选择txt,.txt格式")
  18.     if input_file_path:
  19.         input_file.set(input_file_path)
  20.         input_file_label.config(text=input_file_path.split('/')[-1])

  21. def select_target_folder():
  22.     global tar_folder_path
  23.     tar_folder_path = filedialog.askdirectory(title="请选择输出文件夹")
  24.     if tar_folder_path:
  25.         target_folder.set(tar_folder_path)
  26.         target_folder_label.config(text=tar_folder_path.split('/')[-1])


  27. def run():
  28.     global input_file_path
  29.     global tem_file_path
  30.     global tar_folder_path
  31.     global df_merge
  32.     status_label.config(text="正在运行中,请稍候")
  33.     root.update()
  34.     time.sleep(2)  # 模拟命令执行时间
  35.     status_label.config(text="已完成")

  36.     input_file = input_file_path
  37.     template_file = tem_file_path
  38.     target_folder = tar_folder_path

  39.     # 读取txt文件内容,转换为DataFrame

  40.     with open(input_file, 'r', encoding='utf-8') as f:
  41.         lines = f.readlines()
  42.     data = [line.strip().split() for line in lines]
  43.     columns = ['管线号', '焊缝编号', '焊接类型', '主要信息', '管线寸口']
  44.     df = pd.DataFrame(data, columns=columns)

  45.     # 对列“焊缝编号”的第一个字符去除
  46.     df['焊缝编号'] = df['焊缝编号'].str[1:]
  47.     # 对列“焊接类型”的数据进行替换
  48.     df['焊接类型'] = df['焊接类型'].replace(
  49.         {'BW': '对焊', 'LET': '开口焊', 'SW': '承插焊', 'SOF': '承插焊', 'SOB': '承插焊'})
  50.     df['主管外径'] = df['主要信息'].apply(lambda x: x[1:x.find('*')])
  51.     df['支管外径'] = df['主管外径']
  52.     df['壁厚'] = df['主要信息'].apply(lambda x: x[x.find('*') + 1:x.find(',')])
  53.     df['支管壁厚'] = df['壁厚']
  54.     df['焊缝前材质'] = df['主要信息'].apply(lambda x: x[x.find(',') + 1:]) + "-"
  55.     df['焊缝后材质'] = df['焊缝前材质']
  56.     df['弯头焊点标识'] = "-"
  57.     df['管线寸口'] = ""
  58.     # 将DataFrame写入Excel文件
  59.     excel_file = f"{target_folder}/转换后excel.xlsx"
  60.     df.to_excel(excel_file, index=False)


  61. root = tk.Tk()
  62. root.title("江苏瑞鼎 CADWORK的txt文件转excel程序")
  63. root.geometry("600x500+100+100")
  64. # 设置窗口锁定缩放,可以传两个bool值,指定能否缩放,True是可以拉伸的。
  65. root.resizable(False, False)
  66. # 设置窗口置顶,用的到,可以用
  67. root.attributes("-topmost", True)

  68. input_file = tk.StringVar()
  69. template_file = tk.StringVar()
  70. target_folder = tk.StringVar()

  71. # 创建按钮组件 Button,注意这里都是写函数名,不加()
  72. tk.Button(root, text="1、选择txt格式,格式为.txt", width=32, command=select_input_file, font=("黑体", 20)).place(x=20, y=20)
  73. input_file_label = tk.Label(root, text="",width=40,font=("楷体", 20))
  74. input_file_label.place(x=20, y=70)


  75. tk.Button(root, text="2、选择输出位置,格式为文件夹", width=35, command=select_target_folder, font=("黑体", 20)).place(
  76.         x=20, y=120)
  77. target_folder_label = tk.Label(root, text="",width=40,font=("楷体", 20))
  78. target_folder_label.place(x=20, y=170)

  79. # 填写一个运行的按钮
  80. tk.Button(root, text="3、前面完成输入,按此运行", width=30, command=run, font=("黑体", 20)).place(
  81.         x=20, y=220)

  82. status_label = tk.Label(root, text="等待中",width=30,font=("楷体", 20))
  83. status_label.place(x=20, y=270)

  84. version_label = tk.Label(root, text="软件版本:V1.0 20241031",width=30,font=("宋体", 20)).place(x=20, y=350)
  85. author_label = tk.Label(root, text="制作:朱宁",width=30,font=("宋体", 20)).place(x=20, y=400)

  86. # 开启窗口对象
  87. root.mainloop()

复制代码

报错好像是tkinter得到类型错误
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\tkinter\__init__.py", line 1967, in __call__
    return self.func(*args)
           ^^^^^^^^^^^^^^^^
  File "D:\PYTHON_NEW\pack20240926\pythonProject1\cadworx_excel.py", line 57, in run
    lines = f.readlines()
            ^^^^^^^^^^^^^
  File "<frozen codecs>", line 322, in decode
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb9 in position 15: invalid start byte



test.txt

14.77 KB, 下载次数: 0

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2024-11-4 10:33:16 | 显示全部楼层
根据您提供的错误信息,问题出在读取txt文件时的编码问题。错误提示 `UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb9 in position 15: invalid start byte` 表示在使用UTF-8编码读取文件时遇到了无法解码的字节。

以下是一些可能的解决方案:

1. **尝试不同的编码**:如果txt文件不是UTF-8编码,可以尝试使用其他常见编码,如GBK或ISO-8859-1。

  
  1. with open(input_file, 'r', encoding='gbk') as f:
  2.        lines = f.readlines()
复制代码


2. **自动检测编码**:使用`chardet`库来自动检测文件的编码。

   首先安装`chardet`库:

  
  1. pip install chardet
复制代码


   然后在代码中使用:

  
  1. import chardet

  2.    with open(input_file, 'rb') as f:
  3.        raw_data = f.read()
  4.        result = chardet.detect(raw_data)
  5.        encoding = result['encoding']

  6.    with open(input_file, 'r', encoding=encoding) as f:
  7.        lines = f.readlines()
复制代码


3. **忽略错误**:如果文件中只有少量无法解码的字符,可以选择忽略这些错误。

  
  1. with open(input_file, 'r', encoding='utf-8', errors='ignore') as f:
  2.        lines = f.readlines()
复制代码


尝试以上方法之一,看看是否能解决问题。如果问题依然存在,请检查txt文件的实际编码格式,确保使用正确的编码进行读取。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-11-4 10:43:33 | 显示全部楼层
Exception in Tkinter callback
Traceback (most recent call last):
  File "D:\PYTHON_NEW\pack20240926\pythonProject1\.venv\Lib\site-packages\pandas\core\internals\construction.py", line 939, in _finalize_columns_and_data
    columns = _validate_or_indexify_columns(contents, columns)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\PYTHON_NEW\pack20240926\pythonProject1\.venv\Lib\site-packages\pandas\core\internals\construction.py", line 986, in _validate_or_indexify_columns
    raise AssertionError(
AssertionError: 5 columns passed, passed data had 6 columns

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\tkinter\__init__.py", line 1967, in __call__
    return self.func(*args)
           ^^^^^^^^^^^^^^^^
  File "D:\PYTHON_NEW\pack20240926\pythonProject1\cadworx_excel.py", line 69, in run
    df = pd.DataFrame(data, columns=columns)
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\PYTHON_NEW\pack20240926\pythonProject1\.venv\Lib\site-packages\pandas\core\frame.py", line 851, in __init__
    arrays, columns, index = nested_data_to_arrays(
                             ^^^^^^^^^^^^^^^^^^^^^^
  File "D:\PYTHON_NEW\pack20240926\pythonProject1\.venv\Lib\site-packages\pandas\core\internals\construction.py", line 520, in nested_data_to_arrays
    arrays, columns = to_arrays(data, columns, dtype=dtype)
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\PYTHON_NEW\pack20240926\pythonProject1\.venv\Lib\site-packages\pandas\core\internals\construction.py", line 845, in to_arrays
    content, columns = _finalize_columns_and_data(arr, columns, dtype)
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\PYTHON_NEW\pack20240926\pythonProject1\.venv\Lib\site-packages\pandas\core\internals\construction.py", line 942, in _finalize_columns_and_data
    raise ValueError(err) from err
ValueError: 5 columns passed, passed data had 6 columns

上面是修改后的报错
  1. """
  2. 首先,我们需要使用Python的tkinter库来创建一个简单的图形界面,让用户选择txt文件和输出文件夹。然后,使用pandas库将txt文件内容读取到DataFrame中,并将数据写入Excel文件。

  3. 解析:
  4. 1. 导入所需库:tkinter、pandas、openpyxl
  5. 2. 创建图形界面,让用户选择txt文件和输出文件夹
  6. 3. 读取txt文件内容,将其转换为DataFrame
  7. 4. 将DataFrame写入Excel文件

  8. 代码如下:

  9. ```python
  10. """
  11. import pandas as pd
  12. import tkinter as tk
  13. from tkinter import filedialog
  14. from tkinter import ttk
  15. import time
  16. from openpyxl import load_workbook
  17. import chardet
  18. input_file_path = ""
  19. tem_file_path = ""
  20. tar_folder_path = ""
  21. df_merge = []

  22. def select_input_file():
  23.     global input_file_path
  24.     input_file_path = filedialog.askopenfilename(filetypes=[("text files", "*.txt")], title="请选择txt,.txt格式")
  25.     if input_file_path:
  26.         input_file.set(input_file_path)
  27.         input_file_label.config(text=input_file_path.split('/')[-1])

  28. def select_target_folder():
  29.     global tar_folder_path
  30.     tar_folder_path = filedialog.askdirectory(title="请选择输出文件夹")
  31.     if tar_folder_path:
  32.         target_folder.set(tar_folder_path)
  33.         target_folder_label.config(text=tar_folder_path.split('/')[-1])


  34. def run():
  35.     global input_file_path
  36.     global tem_file_path
  37.     global tar_folder_path
  38.     global df_merge
  39.     status_label.config(text="正在运行中,请稍候")
  40.     root.update()
  41.     time.sleep(2)  # 模拟命令执行时间
  42.     status_label.config(text="已完成")

  43.     input_file = input_file_path
  44.     template_file = tem_file_path
  45.     target_folder = tar_folder_path

  46.     # 读取txt文件内容,转换为DataFrame
  47.     with open(input_file, 'rb') as f:
  48.          raw_data = f.read()
  49.          result = chardet.detect(raw_data)
  50.          encoding = result['encoding']




  51.     with open(input_file, 'r', encoding= encoding, errors='ignore') as f:
  52.         lines = f.readlines()

  53.     data = [line.strip().split() for line in lines]
  54.     columns = ['管线号', '焊缝编号', '焊接类型', '主要信息', '管线寸口']
  55.     df = pd.DataFrame(data, columns=columns)

  56.     # 对列“焊缝编号”的第一个字符去除
  57.     df['焊缝编号'] = df['焊缝编号'].str[1:]
  58.     # 对列“焊接类型”的数据进行替换
  59.     df['焊接类型'] = df['焊接类型'].replace(
  60.         {'BW': '对焊', 'LET': '开口焊', 'SW': '承插焊', 'SOF': '承插焊', 'SOB': '承插焊'})
  61.     df['主管外径'] = df['主要信息'].apply(lambda x: x[1:x.find('*')])
  62.     df['支管外径'] = df['主管外径']
  63.     df['壁厚'] = df['主要信息'].apply(lambda x: x[x.find('*') + 1:x.find(',')])
  64.     df['支管壁厚'] = df['壁厚']
  65.     df['焊缝前材质'] = df['主要信息'].apply(lambda x: x[x.find(',') + 1:]) + "-"
  66.     df['焊缝后材质'] = df['焊缝前材质']
  67.     df['弯头焊点标识'] = "-"
  68.     # df['管线寸口'] = ""
  69.     # 将DataFrame写入Excel文件
  70.     excel_file = f"{target_folder}/转换后excel.xlsx"
  71.     df.to_excel(excel_file, index=False)


  72. root = tk.Tk()
  73. root.title("江苏瑞鼎 CADWORK的txt文件转excel程序")
  74. root.geometry("600x500+100+100")
  75. # 设置窗口锁定缩放,可以传两个bool值,指定能否缩放,True是可以拉伸的。
  76. root.resizable(False, False)
  77. # 设置窗口置顶,用的到,可以用
  78. root.attributes("-topmost", True)

  79. input_file = tk.StringVar()
  80. template_file = tk.StringVar()
  81. target_folder = tk.StringVar()

  82. # 创建按钮组件 Button,注意这里都是写函数名,不加()
  83. tk.Button(root, text="1、选择txt格式,格式为.txt", width=32, command=select_input_file, font=("黑体", 20)).place(x=20, y=20)
  84. input_file_label = tk.Label(root, text="",width=40,font=("楷体", 20))
  85. input_file_label.place(x=20, y=70)


  86. tk.Button(root, text="2、选择输出位置,格式为文件夹", width=35, command=select_target_folder, font=("黑体", 20)).place(
  87.         x=20, y=120)
  88. target_folder_label = tk.Label(root, text="",width=40,font=("楷体", 20))
  89. target_folder_label.place(x=20, y=170)

  90. # 填写一个运行的按钮
  91. tk.Button(root, text="3、前面完成输入,按此运行", width=30, command=run, font=("黑体", 20)).place(
  92.         x=20, y=220)

  93. status_label = tk.Label(root, text="等待中",width=30,font=("楷体", 20))
  94. status_label.place(x=20, y=270)

  95. version_label = tk.Label(root, text="软件版本:V1.0 20241031",width=30,font=("宋体", 20)).place(x=20, y=350)
  96. author_label = tk.Label(root, text="制作:朱宁",width=30,font=("宋体", 20)).place(x=20, y=400)

  97. # 开启窗口对象
  98. root.mainloop()







复制代码

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-11-4 10:45:27 | 显示全部楼层
颂风侯 发表于 2024-11-04 10:43
Exception in Tkinter callback
Traceback (most rec ...


根据您提供的错误信息,问题出在`pandas.DataFrame`的构造过程中。错误提示 `ValueError: 5 columns passed, passed data had 6 columns` 表示您传递的列数与数据的列数不匹配。

以下是一些可能的解决方案:

1. **检查数据和列的数量**:确保`data`变量中的每一行数据的列数与`columns`变量中的列数一致。

2. **打印调试信息**:在创建DataFrame之前,打印`data`和`columns`的内容,确保它们的结构和数量是正确的。

3. **自动推断列名**:如果txt文件的第一行是列名,可以使用`pandas`自动推断列名。

  
  1. df = pd.read_csv(input_file, sep='\t', encoding=encoding, error_bad_lines=False)
复制代码


4. **手动调整列名**:如果列名和数据不匹配,手动调整`columns`变量以匹配数据的实际列数。

5. **检查数据格式**:确保txt文件中的数据格式正确,尤其是分隔符是否一致。

请根据以上建议检查和调整您的代码。如果问题依然存在,请提供更多关于txt文件格式的信息,以便更好地帮助您解决问题。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-18 17:11

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表