I have the following code so far:
import sys
from Tkinter import *
import tkFileDialog
from tkFileDialog import askopenfile # Open dialog box
fen1 = Tk() # Create window
fen1.title("Optimisation") # Window title
menu1 = Menu(fen1)
def open():
filename = askopenfile(filetypes=[("Text files","*.txt")], mode='r')
filename.seek(0)
numligne = 0
line = []
ok = 0
k = -1
while (ok == 0) & (k == -1):
line = filename.readline()
k = line.find( "*load" )
if k == 0 :
l = filename.readlines()
fen1.mainloop()
The text file I am searching is in the format similar to below:
*test
1 2 3 4
*load
2 7 200
3 7 150
*stiffness
2 9 8 7
etc..
I’ve so far managed to find the line beginning with “*load” but I wish to assign the values in between ‘*load’ and ‘*stiffness’ to variables such as a, b, c. My problem is that in this load section, there could be several lines and I need to detect each one every time, split the values in the lines and give them a name. If someone could please help explain a loop or something similar that would do just the trick, I would be very grateful! Thank you!
UPDATE: I have the problem where I now want to find SEVERAL seperate sections in the same text file. How am I able to create a loop to further find lines between ‘*geo’ and ‘*house’, and also ‘*name’ and ‘*surname’? I’ve tried to create an entirely separate definition but would like to minimize the lines of code I use…Thank you! Code I’ve been using the similar structure for (as provided for my original question, thanks to mgilson!) and would therefore like to edit these type of code.
def parse_file(ff):
out=[]
append=False
for line in ff:
if(append and line.strip()):
out.append(line)
if(line.startswith('*load')):
append=True
elif(line.startswith('*stiffness')):
return [map(int,x.split()) for x in out[:-1] ]
Let’s assume that your “blocks” of code are separated by headers (e.g.
*header). The most intuitive way to store the data in each block is in a list of lists. e.g.[ row1, row2, ...](whererow1=[elem1,elem2,elem3,...]). Then you can store the block in a dictionary so you can get access to the block viablock=dictionary['headername'].This will do something like what you want (this version is untested).
Note that if you’re guaranteed that each row in the datafile under a certain header has the same number of entries, you can think of the variable
infoas a 2-dimensional row which is indexed aselement=info[row_number][column_number]— but you can also get an entire row byrow=info[row_number]