1

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!

1
  • Thank you! Which means to use the following: G = poisson(d['mu']) right after that? Commented Mar 28, 2017 at 17:39

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Following this logic, can I call 'file.mu' / 'file.co' later on to use the variable?
0

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.

4 Comments

Thank you! Following this logic, how can I call mu, cs or co then?
in more detail, G = poisson(f['mu']), you could see usage of dict in Python
Thanks @jerliol I tried that but it says: File "<stdin>", line 1, in <module> KeyError: 'mu' And if I write mu = f['mu'] it returns same error.
try to debug you code due to your file's format may be not same as you said, like my updated code, print is normally simplest way to debug

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.