python - 为什么循环到文件并尝试加入列表后出现错误
问题描述
我有带有数字的大文本文件。我想遍历文件并将数字附加到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')]))
解决方案
看那部分
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))
推荐阅读
- git - 如何按文件类型过滤 repo 的拉取
- python - Leap Motion Controller - 不连接 cpp、python (mac)
- python - 为什么增加 nn.Linear 输入特征的大小会提高 CNN 模型的准确性?
- java - SpringBatch-如何将文件本身作为项目处理?
- c# - 将模型类作为泛型类型参数传递
- calc - 在 Libre Office Calc 中,当右侧边缘无法向内拖动时,如何调整列宽?
- python - 如何将列表转换为字典?
- c# - 删除多对多实体框架(WinForms)
- c++ - 如何转换`std::tuple
` 到 `std::tuple` - python - 将字符串隐藏到 yaml 并在烧瓶中返回响应