-1

I am building a Python code that should read a text file using askopenfile in tkinter in Python. The text file is just a column of numbers:

300.0
250.0 
250.0
250.0
250.0 
270.61032473 
289.91197172 
290.23398559 
275.90792547
263.86956625 
264.8385967

My code is attached below:

from tkinter import * 
from tkinter.ttk import *
import numpy as np
from tkinter.filedialog import askopenfile 

root = Tk() 

t=12
p=np.empty(t)

def open_file(): 
    file = askopenfile(mode ='r', filetypes =[('all files', '*.*')]) 
    if file is not None: 
        global x
        x = file.read() 
        print(x)
        global p
        global count

        #x=x.split('\n')

        #count=0
        #for row in x:

         #   i=float(row[0])#change from string to float type
          #  p[count]=i #updates x array
           # count +=1 # increment of 1 to get the number of total values

        #p=p.reshape(t,1)

        #print(p) 

        return x

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

mainloop() 

When I print x from the command window, the result is the following:

'300.0 \n300.0 \n250.0 \n250.0\n250.0\n250.0 \n270.61032473 \n289.91197172 \n290.23398559 \n275.90792547\n263.86956625 \n264.8385967'

Hence when I print x[0] for instance, the results is only: 3.

I actually want x[0] to be 300.0, x[1] to be 250.0, etc.

In addition to that, I want to convert them to numerical numbers not strings.

AMC
  • 2,642
  • 7
  • 13
  • 35
Mohamad Ibrahim
  • 315
  • 2
  • 8
  • Yes because the code attached is just a small part of a much larger code that has GUI (Tkinter) and Neural Networks my friend.. – Mohamad Ibrahim Feb 09 '20 at 21:05
  • 1
    `import *` is generally bad practice. Why do you declare so many global variables, instead of returning the values? – AMC Feb 09 '20 at 21:17
  • Also, couldn't you simplify `command = lambda:open_file()` to `command=open_file`? Finally, from the code you commented out, I don't think you need to use NumPy here. – AMC Feb 09 '20 at 21:22
  • Does this answer your question? [How to split a string of space separated numbers into integers?](https://stackoverflow.com/questions/6429638/how-to-split-a-string-of-space-separated-numbers-into-integers) – AMC Feb 09 '20 at 21:28
  • This is a duplicate of the above ^ , the only difference is the character to split on, which is trivial. – AMC Feb 09 '20 at 21:29

1 Answers1

3

To parse the string x

x = '300.0 \n300.0 \n250.0 \n250.0\n250.0\n250.0 \n270.61032473 \n289.91197172 \n290.23398559 \n275.90792547\n263.86956625 \n264.8385967'

into a list of numbers, you could do:

x_as_list_of_numbers = [float(xx.strip()) for xx in x.split('\n')]
Arco Bast
  • 3,595
  • 2
  • 26
  • 53