Python 将*.dat中的数据保存到不同列表中
我有一个.dat文件,我需要在Pyton 3.7中为第一列创建一个列表变量,为第四列创建另一个变量Python 将*.dat中的数据保存到不同列表中,python,list,Python,List,我有一个.dat文件,我需要在Pyton 3.7中为第一列创建一个列表变量,为第四列创建另一个变量 from tkinter import * from tkinter.ttk import * from tkinter.filedialog import askopenfile root = Tk() root.geometry('200x100') def open_file(): file = askopenfile(mode ='r', filetypes =[('Meas
from tkinter import *
from tkinter.ttk import *
from tkinter.filedialog import askopenfile
root = Tk()
root.geometry('200x100')
def open_file():
file = askopenfile(mode ='r', filetypes =[('Measurement Files', '*.dat')])
content = file.read()
cols = [[], [], [], [], []]
for line in content.split('\n'): # loop over all data lines
for n, col in enumerate(line.split()): # split each line into five columns and loop over
cols[n].append(float(col)) # convert each data to float and append to corresponding column
print(cols)
btn = Button(root, text ='Open', command = lambda:open_file())
btn.pack(side = TOP, pady = 10)
mainloop()
这是我的代码,它将列拆分到不同的列表中,但是,如何为第一个列表创建一个变量,为第四个列表创建另一个变量?一旦我尝试:
time=cols[0]
head=cols[3]
它表示没有定义“cols”
cols
是只存在于函数内部的局部变量,您必须在函数中使用全局cols
为外部/全局变量赋值
其他更改的最小示例
#from tkinter import * # `import *` is not preferred
import tkinter as tk
from tkinter.filedialog import askopenfile
# --- functions ---
def open_file():
global time # inform function to assign value to external/global variable
global head # inform function to assign value to external/global variable
file = askopenfile(mode='r', filetypes=[('Measurement Files', '*.dat')])
content = file.read()
time = [] # assing value to global variable
head = [] # assing value to global variable
for line in content.split('\n'): # loop over all data lines
items = line.split() # split each line into five columns and loop over
if len(items) >= 4:
time.append(float(items[0]))
head.append(float(items[3]))
#print(time) # get value from global variable
#print(head) # get value from global variable
# --- main ---
root = tk.Tk()
root.geometry('200x100')
btn = tk.Button(root, text='Open', command=open_file)
btn.pack(side='top', pady=10)
root.mainloop()
print(time) # get value from global variable
print(head) # get value from global variable
您在哪里尝试导致错误的代码?请分享完整的回溯。你看过文件了吗?我不熟悉tkinter,但它似乎是一个更好的选择,因为您的数据是以制表符分隔的格式。如果您只需要两列,那么您只能创建两个列表
time=[]
和head=[]
并跳过内部循环-items=line.split()
time.append(float(项[0]))
head.append(float(项[4]))
在哪里使用time=cols[0]
?变量cols
是局部变量,不存在于open\u文件()之外
。如果您需要外部变量,请在函数中使用全局cols
通知函数使用外部/全局变量而不是本地变量。您可以使用命令=打开\u文件
而不使用lambda
和()
非常感谢,我添加了此修改,但仍然得到一个错误:time.append(float(items[0]))索引器:列表索引超出范围我没有您的文件来测试它。可能有些行是空的。我在获取[0]
和[3]
之前添加了如果len(items)>=4: