I have a text file that I need to find data and assign it to a variable. I have found code to read and search a file but the information I want is not always constant. The Items in Red will change. Is there a way to find this information, maybe by position and assign it to a variable? EX.FCITC = 690.4

Sorry if I was suppose to wrap the text files with the code tags I was not sure, because it was not code.
Thanks,
Joe

Study transfer. From FMPP_EXA To FPL_IMA . Transfer level - 1000.0 MW


Violations report ordered by transfer capability. Total 3 violations


FCITC TDF LODF <--------- Limiting constraint ---------> <--------- Contingency description ---------> Ncon PreShift Rating PTDF IntBase FnlBase
690.4 -0.12312 - 5567 IND RIV 115 B$0029 CTAB GSU 1.00 1 Base Case 0.0 -85.0

Study transfer level - 1000.0 MW. Total violations: 21
First violation - -756.5 MW.

Dani AI

Generated

A reliable approach is to treat each transfer block as a unit: detect the header that names the path, remember that as the current key, then capture the FCITC numeric value(s) that belong to that header. 's line-by-line idea is the right starting point, but real files often have blank lines, variable spacing, or multiple FCITC entries per path — so use a small state machine (remember current path, set a flag when you hit the FCITC label, then parse the next numeric-bearing line) and store results in a dictionary keyed by the path name.

Use regex for robust number extraction and convert tokens to floats inside a try/except so bad tokens don't crash the script. Keep each path's measurements in a list (append as you find them) so you can later take the first, max, or average as needed. If the path header is present (a "From ... To ..." line in the sample), build a descriptive key (for example From_To) rather than inventing numbered variables; dictionaries are safer and self-documenting.

Example parser outline (different from the earlier snippet) — it keeps state and handles FCITC appearing on its own line or immediately before the numbers:

import re

header_re = re.compile(r'From\s+(\S+)\s+To\s+(\S+)', re.I)
num_re = re.compile(r'[+-]?\d+(?:\.\d+)?')

results = {}
current = None
expect_value = False

with open('yourfile.txt') as fh:
    for line in fh:
        h = header_re.search(line)
        if h:
            current = h.group(1) + '_' + h.group(2)
            results.setdefault(current, [])
        if 'FCITC' in line:
            expect_value = True
            continue
        if expect_value:
            m = num_re.search(line)
            if m and current:
                try:
                    results[current].append(float(m.group()))
                except ValueError:
                    pass
            expect_value = False

Troubleshooting in Visual Studio: print the results before the script exits, verify the working directory or use an absolute path, run the file from a console to see output and exceptions, and add a short pause (or run without debugging) so the window doesn't close immediately. Finally, document any assumptions — if the file format changes, the regex/state logic will need small tweaks.

Recommended Answers

All 5 Replies

I'm posting this for others so they can see what your input file actually looks like.

Study transfer. From FMPP_EXA To FPL_IMA . Transfer level - 1000.0 MW


Violations report ordered by transfer capability. Total 3 violations


FCITC TDF LODF <--------- Limiting constraint ---------> <--------- Contingency description ---------> Ncon PreShift Rating PTDF IntBase FnlBase
690.4 -0.12312 - 5567 IND RIV 115 B$0029 CTAB GSU 1.00 1 Base Case 0.0 -85.0

Study transfer level - 1000.0 MW. Total violations: 21
First violation - -756.5 MW.

Are you always looking for the first item on the line after FCITC, TDF, etc? So in this case, your code could scan the file line by line looking for FCITC. Once that is found, we look at the following line and get the first item (in this case, 690.4). Store it to a variable and then continue.

Is that right?

Yes that is correct. I don't know how to do that.

[

I would suggest something like this:

# Open the file
f = open('myfile.txt')
# Read all the lines into a list
lines = f.readlines()
# Close the file
f.close()

# Now iterate over each line in the file until we find FCITC
for idx, line in enumerate(lines):
    if len(line) and line.split()[0] == 'FCITC':
        # Now our data will be on the line idx+1
        data = lines[idx+1].split()[0]

print data

I will give that a try. Hopefully I can respond today with the results but I am working all day but if not today definately tomorrow.
Thank,
Joe

I can't seem to get this to work. I am trying to run it in visual studio, and it seems to run but it does not give me an output. Just reading the code, I can see that it splits the data and it seems to grab the data but does it save the data to something I can use later? Like if I wanted to check if FCITC was >0. Also after it reaches FCITC does it check for additional FCITC's?. Since the sample file I sent in shows 10 different FCITC paths how do I know which FCITC is being represented. I guess I did not make that part clear either. The first path is for FMPP_EXA to FPL IMA and the FCITC for that path is 690.4. Since the output file is probably going to always stay consistant I was thinking of making this something like Data 1 = 690.4, but it could as easily been FMPP_FPL_FCITC=690.4.


On a different subject. You said that you had to reformat my text data so that other users could view it. What did I do wrong? I am new and do not know much about BBcode, and would really like to learn so I can make it as easy as possible for people trying to help me.
Thanks for your posts, I will keep trying to get it to run.
Joe

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.