Reputation: 297
I just started Python and would like to read the following text file and use the variable values:
Textfile 'r1': (Variable name and its value)
mu | cs | co
------------------
5 | 100| 300
------------------
I have the following code:
with open("r1.txt") as file1: data = file1.read()
it could be printed but f returns no value.
How could I use the variable in the text file for later use (mu, cs, co)?
Ex: I would like to generate a poisson distribution,
Can I write:
G = poisson(data.mu)
It seems not, but how could I call the corresponding varilables in the dataset?
Thank you!
Upvotes: 1
Views: 3026
Reputation: 195
You should read two lines first, then parse them, and finally use it as dict
with open("r1.txt") as fp:
lines = [line for line in fp]
keys = [s.strip() for s in lines[0].split('|')] # key line
vals = [s.strip() for s in lines[2].split('|')] # value line
f = dict(zip(keys, vals))
print(f)
then, you could use f['mu']
for then mu value.
Upvotes: 0
Reputation: 462
After you used the read
function (in the print
command), the file has already been read, so second reading gives nothing. You should assign reading to some variable, such as
with open("r1.txt") as file:
lines = file.read()
so that you can go back to lines
in the future.
But if you want to assign specific variables to specific values read from file, you need to parse it. Here, it depends heavily on the specific format your data is in.
Upvotes: 1