0

I have a file input.dat with contents:

1.00000000   1.00000000   0.00000000   0.10000000        12        12     50000           2

I want to read these values and assign them to variables a1 to a8 respectively.

I try:

with open("input_params.dat","r") as inpfl:
    a1,a2,a3,a4,a5,a6,a7,a8 = inpfl.read()

and get the error:

ValueError: too many values to unpack (expected 8)

How can I modify read() to do what I want?

I also need a1,..., a8 to be floats and integers respectively and not string variables. How do I accomplish this?

2
  • 4
    inpfl.read().split() Commented Nov 3, 2019 at 17:17
  • Do not use a1, a2, ..., a8. Either use sensible names or use a list. Commented Nov 3, 2019 at 17:22

1 Answer 1

3

you can just use below code:

f = open('1.txt' , 'r')
lines = f.read().split(" ")

so you have list of values and you can take it in variable if you want like below: a = lines[0], b = lines[1] and so on.

You can use a1,a2,a3 = f.read().split(" ") if you want it in variables. Provided you have exact number of variables as values in file.

Hope this helps.

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

5 Comments

thanks, it does help in case I want the variables on a list
You can use a1,a2,a3 = f.read().split(" ") if you want it in variables.
yes, it was mentioned above and it's what I need. Thanks again
This way, a1 to a8 are string variables. I need them to be floats and integers respectively. How can I accomplish this?
As your file will always return string when you read from it, you will have to manually convert the values accordingly. I think all you can convert all values to the float as 12.0 is as good as 12. You can use a1,a2,a3...= float(f.read().split(" ")). If you want it to be int and float resp then you have to manually do float() or int()

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.