首页 > 解决方案 > 为什么循环到文件并尝试加入列表后出现错误

问题描述

我有带有数字的大文本文件。我想遍历文件并将数字附加到list_of_numbers。问题是循环附加到列表但不是我想要的方式,这就是为什么列表在迭代后看起来像这样

['\n', '+', '1', '6', '1', '0', '8', '5', '0', '7', '7', '6', '4', '\n', '+', '1', '6', '1', '0', '7', '6', '4', '6', '0', '2', '9', '\n', '+', '1', '6', '1', '0', '7', '6', '4', '6', '8', '4', '6', '\n', '+', '1', '6', '1', '0', '8', '5', '0', '5', '9', '3', '4', '\n', '+', '1', '6', '1', '0', '7', '6', '4', '0', '7', '8', '3', '\n', '+', '1', '6', '1', '0', '7', '6', '4', '9', '2', '8', '2', '\n', '+', '1', '6', '1', '0', '7', '6', '4', '0', '0', '4', '9', '\n']

这只是输出的一部分。我希望这是这种类型 [123455334,492023232,32322323]

我试图这样做,但它不起作用并出现错误

print(list([int(x) for x in ''.join(list_of_numbers).split('\n')]))

这是我的完整代码

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
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)
    tf = open(tf)  # or tf = open(tf, 'r')
    data = tf.read()
    txtarea.insert(END, data)
    tf.close()
    for i in data:
        list_of_numbers.append(i)



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()

print(list_of_numbers)


while ' ' in list_of_numbers:
    list_of_numbers.remove(' ')

print(list([int(x) for x in ''.join(list_of_numbers).split('\n')]))

标签: pythonpython-3.xlistfiletkinter

解决方案


看那部分

tf = open(tf)  # or tf = open(tf, 'r')
data = tf.read()
txtarea.insert(END, data)
tf.close()
for i in data:
    list_of_numbers.append(i)

data是一大串。然后你一次迭代一个字符并附加那个单个字符(包括,'+''\n'到列表中。所以你得到你得到的。

将上面的代码段替换为以下代码:

with open(tf) as f: # use context manager
    for line in f:
        txtarea.insert(END, line)
        list_of_numbers.append(int(line))

请注意,这假设您的文件中没有空行。如果有,那么

with open(tf) as f: # use context manager
    for line in f:
        txtarea.insert(END, line)
        line = line.strip()
        if line:
            list_of_numbers.append(int(line))

推荐阅读