【问题标题】:How can I create a variable with data readed with tkinter? Tkinter openfile and create variables of the data如何使用 tkinter 使用数据读取器创建变量? Tkinter 打开文件并创建数据变量
【发布时间】:2020-04-14 22:04:10
【问题描述】:
from tkinter.filedialog import askopenfile 
root = Tk() 
root.geometry('200x100') 


def open_file(): 
    file = askopenfile(mode ='r', filetypes =[('Measurement Files', '*.dat')]) 
    if file is not None: 
        content = file.read() 
        print(content) 

btn = Button(root, text ='Open', command = lambda:open_file()) 
btn.pack(side = TOP, pady = 10) 

mainloop()

Python 3.7 版 代码正在返回文件的内容,但是如何将每列数据保存到不同的变量中?

数据文件结构如图:

enter image description here

我想用每列的数据创建 5 个列表。

【问题讨论】:

  • 你应该给我们数据文件的结构,或者最好显示一些示例数据文件。您说的是“数据列”,所以可能是某种 CSV 方言?
  • 数据文件为.dat扩展名,由5列数据组成(无标题):
  • 700.00000 0.09300 1.05161 320.52990 31.43325 701.00000 0.09277 1.04902 319.74106 31.35589 702.00000 0.09163 1.03608 315.79689 30.96910 703.00000 0.09293 1.05074 320.26695 31.40746 704.00000 0.09583 1.08353 330.25886 32.38733 跨度>
  • 每行第五列后是否有换行符? (这在您的示例中没有显示,但在发布评论时可能已被删除)
  • 我添加了一张关于数据结构的图片,从每一列我需要创建一个数据列表。

标签: python-3.x variables tkinter import


【解决方案1】:

这是一个解决方案,将数据文件解析为五个列表的列表,其中每个内部列表包含一列数据:

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

编辑(在您发表评论后):

如果你真的需要 5 个不同的变量来存储你的 5 列,你可以简单地在我之前的代码之后添加以下行:

a, b, c, d, e = cols

【讨论】:

  • 谢谢!但是在这里我们分成列,但它们没有归因于任何变量,对吧?如何将拆分后的数据保存在不同的变量中?
  • 它将它们添加到单个多维 cols 数组中。要访问第一列,您将使用cols[0]。第一列中的第一项将是 cols[0][0],然后是 cols[0][1],依此类推。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-15
  • 1970-01-01
  • 1970-01-01
  • 2019-04-22
  • 1970-01-01
相关资源
最近更新 更多