python—为什么我在循环到文件并尝试加入列表后出错

os8fio9y  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(423)

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

['\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']

这只是输出的一部分。我希望它是这种类型的[12345533449202323232322323]
我试图这样做,但它不工作,并得到错误

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')]))
qfe3c7zg

qfe3c7zg1#

看看那部分

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

相关问题