Simontaga
Simontaga

Reputation: 65

Python 3, Read textfile and separate each line and fill in corresponding variables

Firstly I use this:

with open(filename) as fp:
    for i, line in enumerate(fp):    
        print(i)
        print(line)
        if i == index:
            break
        else:
            continue

This makes me able to output each line until ( i ) reaches the amount of the index variable, but this is not all I want, I want to read a file which looks a bit like this :

John|Graham|JOB|AGE
Philip|Jefferson|JOB|AGE

I want to be able to parse this data into corresponding variables, but! I want to be able to specify which line to read from, so that I can read line 1, parse the data from there, and then line 2, but not as in a loop!, which is the important part.

I want to be able to set the variable ( index ) to let's say 2

then line 2 will parse the first segment "Philip" into the variable NAME.

and so on.

I hope you understand!, I have been so frustrated that I have not been able to come up with a solution.

Upvotes: 2

Views: 2755

Answers (2)

Riley Martine
Riley Martine

Reputation: 303

Here's something that should work:

first we need to get all the lines read into a list.

>>> with open('in.txt', 'r') as f:
>>>     lines = f.read().splitlines()

now we can index nicely in:

>>> print(lines[0])
    John|Graham|JOB|AGE

Okay, now we want to split each line into the data we need.

>>> first = lines[0]
>>> info = first.split('|')
    ['John', 'Graham', 'JOB', 'AGE']

And then to put everything into a variable:

>>> NAME, LASTNAME, JOB, AGE = info
>>> print(NAME)
    John
>>> print(LASTNAME)
    Graham

Putting it all together:

with open('in.txt', 'r') as f:
    lines = f.read().splitlines()

def get_info(lines, line_num):
    line = lines[line_num]
    return line.split('|')

NAME, LASTNAME, JOB, AGE = get_info(lines, 0)
print(NAME) # Prints "John"

If you don't want to read in the whole file at once, you can use the same techniques in your script:

with open(filename) as fp:
    for i, line in enumerate(fp):    
        print(i)
        print(line)
        if i == index:
            NAME, LASTNAME, JOB, AGE = line.split('|')
            break

Upvotes: 3

Ajax1234
Ajax1234

Reputation: 71461

You can use a dictionary to allow you to access each line by index:

the_dict = {i:a.strip('\n') for i, a in enumerate(open('filename.txt'))}

Output:

{0: 'John|Graham|JOB|AGE', 1: 'Philip|Jefferson|JOB|AGE'}

Upvotes: 0

Related Questions