some_user_3
some_user_3

Reputation: 413

How can i extract data from a .txt file and store it in 2 separate variables?

I would like to extract data from a .txt() file, and then be able to store the two different items (wooden bow and 10) in two separate variables. For example:

var1 = 'wooden bow'
var2 = 10

and the .txt file would look like this:

wooden bow, 10

how would i go about this?

Upvotes: 0

Views: 119

Answers (2)

ti7
ti7

Reputation: 18792

Open the file for reading, then iterate over the lines, reading the vars' values out with .split()

with open("myfile.txt") as fh:  # fh is now a file-like object
    for line in fh:  # text file-likes are iterable by-line!
        var1, var2 = line.split(",")  # line is a string
# file is now closed when you leave the with scope!

This works because .split() returns a list, which can be directly used for assignment (if you have an equal number of members!)

>>> var1, var2 = "wooden bow, 10".split(",")
>>> var1
'wooden bow'
>>> var2
' 10'

Do note, that you'll want to do some cleanup too, such as making numbers into integers or similar

>>> var2 = int(var2)
>>> var2
10

As commented, this may be a good case for a CSV (or JSON) structure!

You will almost-certainly also wish to add some error-handling, which could be as simple as checking that the line doesn't raise an Exception, as complex as verifying the content with a regular expression, both, or inbetween!

Upvotes: 2

gen_Eric
gen_Eric

Reputation: 227220

A comma-separated file, even one as simple as this, is a csv file.

import csv

with open('file.txt') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        var1, var2 = map(lambda s: s.strip(), row)

Upvotes: 0

Related Questions