Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8074851
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T14:47:38+00:00 2026-06-05T14:47:38+00:00

I have the following code so far: import sys from Tkinter import * import

  • 0

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] ] 
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T14:47:41+00:00Added an answer on June 5, 2026 at 2:47 pm

    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, ...] (where row1=[elem1,elem2,elem3,...]). Then you can store the block in a dictionary so you can get access to the block via block=dictionary['headername'].

    This will do something like what you want (this version is untested).

    import sys
    
    def convert_type(ss):
        try:
            return int(ss)
        except ValueError:
            try:
                return float(ss)
            except ValueError:
                return ss
    
    def parse_file(ff):
        out={}
        block=None
        for i,line in enumerate(ff):
            #Allow for comments to start with '#'.  We break off anything after a '#'
            #and ignore it.  After that, we 
            data=line.split('#',1)
            line=data[0]  #comments (if in line) are in data[1] ... ignore those.
            line=line.strip() #remove whitespace from front and back of line.
            if(line.startswith('*')):
                #python supports multiple assignment.  
                #e.g. out['header'] is the same object as block.  
                #     changing block also changes out['header']
                block=out[line.strip()[1:]]=[]
            elif (block is not None) and line: #checks to make sure there is an active block and the line wasn't empty.
                #If the file could also have floats, you should use float instead of int
                #We also put the parsing in a try/except block.  If parsing fails (e.g. a
                #element can't be converted to a float, you'll know it and you'll know the
                #line which caused the problem.)
                try:
                    #block.append(map(int,line.split()))
                    block.append(map(convert_type,line.split()))  
                except Exception:
                    sys.stderr.write("Parsing datafile choked on line %d '%s'\n"%(i+1,line.rstrip()))
                    raise
        return out
    
    with open('textfile.txt','r') as f:
        data_dict=parse_file(f)
    
    #get information from '*load' block:
    info=data_dict['load']
    for row in info:
        a,b,c=row
        ##same as:
        #a=row[0]
        #b=row[1]
        #c=row[2]
        ##as long as row only has 3 elements.
    
        #Do something with that particular row. 
        #(each row in the 'load' block will be visited once in this loop)
    
    #get info from stiffness block:
    info=data_dict['stiffness']
    for row in info:
        pass #Do something with this particular row.
    

    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 info as a 2-dimensional row which is indexed as element=info[row_number][column_number] — but you can also get an entire row by row=info[row_number]

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have to following code and as far as I know it is correct,
I have following code for loading image from url in xml parsing endElement method
I have the following test code. import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; class MyTask
So I have the following code: import java.lang.Thread; import java.lang.Integer; class MyThread extends Thread
I have the following code generated by Eclipse (.java file). import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Display;
I've consulted a similar thread to the following code that I have so far.
I have the following multi-table inheritance situation: from django.db import Models class Partner(models.Model): #
I have following code in initialization im = imread('Image02.tif'); figure(); imagesc(im); colormap(gray); [hImage hfig
I have following code <div id=main> <div id=one> </div> <div id=two> </div> <div id=three>
I have following code for updating user's column public void UpdateLastModifiedDate(string username) { using

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.