-3

I'm trying to take a file that have and take whatever number is on line one (and two and three, etc.) and assign them to a given variable. So say my file is just like:

1
5
6
1

So then how would I take line one and assign that value to variable_a within my code, then take line two and assign it to variable_b. Thanks!

  • 3
    First off, reading from a file: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files – Celeo Oct 13 '15 at 22:50
  • Possible duplicate of [Unicode (utf8) reading and writing to files in python](http://stackoverflow.com/questions/491921/unicode-utf8-reading-and-writing-to-files-in-python) – Will Oct 14 '15 at 01:01

2 Answers2

0
with open(fname) as f:
    content = f.readlines()
    numbers = [int(x) for x in content]
mescarra
  • 695
  • 5
  • 16
0

Try this:

import string
fi = open(fname, "r")
vars = fi.read()
fi.close()

pos = 0
for i in vars.split("\n"):
    exec('variable_' + string.lowercase[pos] + '=' + i)
    pos += 1

print(variable_b) # will print 5
bitfhacker
  • 292
  • 1
  • 13