循环读取含数字的大文本文件后列表格式异常及转换报错问题排查
问题分析
你遇到的核心问题是读取文件时错误地遍历了每个字符,而不是按行读取完整的数字。for i in data:会把文本中的每一个字符(包括换行符\n、加号+)都单独添加到列表里,所以最终得到的是单个字符的集合,而不是你期望的完整数字元素。
解决方案
我们需要修改文件读取后的处理逻辑,直接按行读取并处理每一行的完整数字:
关键修正点
- 不要逐个字符遍历
data,而是用data.splitlines()按行分割文本,拿到每一行的完整内容 - 过滤掉空行(避免文件末尾换行产生的空字符串干扰)
- 直接把每一行的字符串转成整数(Python的
int()函数可以处理带+号的正数字符串,比如int("+16108507764")会自动转换为16108507764)
修改后的完整代码
from tkinter import * from tkinter import filedialog import selenium import time from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium import webdriver list_of_numbers = [] full_list_of_numbers = [] def openFile(): tf = filedialog.askopenfilename( initialdir="C:/Users/MainFrame/Desktop/", title="Open Text file", filetypes=("Text Files", "*.txt"),) pathh.insert(END, tf) with open(tf, 'r') as tf_file: # 用with语句自动管理文件关闭,更安全 data = tf_file.read() txtarea.insert(END, data) # 核心修改:按行处理数据 for line in data.splitlines(): cleaned_line = line.strip() # 去掉行首尾的空白字符(空格、换行等) if cleaned_line: # 跳过空行 list_of_numbers.append(int(cleaned_line)) print(list_of_numbers) ws = Tk() ws.title("PythonGuides") ws.geometry("400x450") ws['bg']='#fb0' txtarea = Text(ws, width=40, height=20) txtarea.pack(pady=20) pathh = Entry(ws) pathh.pack(side=LEFT, expand=True, fill=X, padx=20) Button( ws, text="Open File", command=openFile ).pack(side=RIGHT, expand=True, fill=X, padx=20) ws.mainloop() # 此时list_of_numbers已经是整数列表,无需额外处理 print(list_of_numbers)
为什么你之前的转换代码会报错?
你尝试的print(list([int(x) for x in ''.join(list_of_numbers).split('\n')]))会报错,是因为拆分后会出现空字符串(比如文件开头或结尾的换行),而int("")是不合法的操作,会触发ValueError。上面的方案从根源上跳过了空行,避免了这个问题。
内容的提问来源于stack exchange,提问作者user16334850
相关产品推荐
相关产品推荐

