user3667966
user3667966

Reputation: 11

How to write multiple variables to a file with python?

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!

Upvotes: 1

Views: 2866

Answers (4)

tpcstld
tpcstld

Reputation: 39

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()

Upvotes: 0

Blckknght
Blckknght

Reputation: 104682

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))

Upvotes: 1

flycee
flycee

Reputation: 12716

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)

Upvotes: -1

Daniel Roseman
Daniel Roseman

Reputation: 599470

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.

Upvotes: 1

Related Questions