1

I am trying to write multiple variables in one file. And would like to avoid to write all the variables and their type seperately.

I created the varibales with:

for i in range(100):
    globals()['doc%s' %i] = 5.*i

to write it to the file:

df = open("test.csv")
df.write("%0.10.f;%0.10.f" % (doc1, doc2))

But i would like to avoid to write within the last line all 100 names with the types.

Is this possible? Does anyone have an idea? Thank you!

3
  • I don't understand - you want to avoid doing what the last line does? You could delete that line...although it doesn't write the types... Commented Mar 16, 2015 at 9:01
  • Are you sure you mean "avoid"? Commented Mar 16, 2015 at 9:02
  • It's worth noting that you're only ever writing one line -- one long line. Commented Mar 16, 2015 at 9:03

4 Answers 4

1

Your problem is that you are dynamically creating variables in the first place. There is really never a good reason to do this. Just create a single doc dict, and then you can write that out to the file.

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

Comments

1

You shouldn't use 100 variables for this. Instead, use a list with 100 values in it. Then you can simply iterate over the list (or pairs of values from the list) and write the values out as you go.

doc = [5.*i for i in range(100)]
pairs = zip(*[iter(doc)]*2)
with open("test.csv") as df:
    for a, b in pairs:
        df.write("{0.10f};{0.10f}\n".format(a, b))

Comments

0

If you must generate your variables in such a way, you can use a similar globals for-loop to dynamically retrieve the variables again.

For example:

data = [globals()['doc%s' % i] for i in range(100)]

puts the variables (doc0 ... doc99) into a list named data. You can then manipulate the list to print it in a format you want.

formatted_data = ["%0.10f" % point for point in data]
df = open("test.csv", "wb")
df.write(";".join(formatted_data))
df.close()

Comments

-1

use eval()

for i in range(100):
    globals()['doc%s' % i] = 5. * i

df = open("test.csv", mode='w')

for i in range(100):
    df.write("%0.10f;" % eval('doc%s' % i))

try it yourself. (My python version 2.7.8)

Comments

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.