Price Nimmich
Price Nimmich

Reputation: 39

Creating a variable for each line in a txt file

I am building a program that will eventually be able to construct finite automata and am in the early stages of reading in the txt file to set up my variables (states, alphabet, starting position, final positions, and rules, respectively). Here is the code I have thus far:

def read_dfa(dfa_filename):
    dfa = open(dfa_filename, 'r')
    count = 0
    for line in dfa:
        count += 1
        states, alphabet, initial, final, rules = (line.format(count, line.strip()))

The issue I am currently facing is that lines 1:4 will always provide the data I need, however, the rules variable could be just line 5, or it could be multiple lines (5:n). How do I make it so I can successfully store the lines I want to each appropriate variable? This is the error I am faced with: 'ValueError: Too many values to unpack (expected 5)' This is an example of what dfa_filename could be:

q1,q2   #states
a,b   #alphabet
q1   #initial
q2   #final
q1,a,q2   #rules
q1,b,q1   #rules
q2,a,q2   #rules
q2,b,q2   #rules

Upvotes: 2

Views: 977

Answers (3)

jeffry_bo
jeffry_bo

Reputation: 21

you can use list to unpack file in list and then get needed lines by index numbers.

file_lines = list(open('textfile.txt'))
states, alphabet, initial, final = file_lines[0:4]
rules = file_lines[4:]

Upvotes: 0

Mitchell Olislagers
Mitchell Olislagers

Reputation: 1817

You could use splitlines and assign the first 4 lines to states, alphabet, initial,and final. Then, assign the remaining lines to rules.

with open('textfile.txt') as input:
    data = input.read()
    states, alphabet, initial, final = data.splitlines()[0:4]
    rules = data.splitlines()[4:]

Upvotes: 1

Florida Man
Florida Man

Reputation: 2147

if I understood correctly, the first 4 are always in this order and then there are multiple rules. And the number of rules can change?

If so, try to unpack with * Operator. This allows to unpack multiple values into one variable:

a, *b = 1, 2, 3

results in a=1 and b=[2, 3]

So it should be something around

states, alphabet, initial, final, *rules = (line.format(count, line.strip()))

Stay save

Upvotes: 0

Related Questions