0

Well, I'm still new to python and I'm a little bit confused of my task right now. I have some Objects given (the amount could be up to 100), and I need to calculate some things for them and save the results in different .txt-files. I did the task only for one Object:

Object = [1., 0., -1.]
repeated_given_time, repeated_given_space, calculated_time_and_space = [], [], []
results = open('Object.txt', 'a')

(here is some omitted code which reads the data from a file (this file remains the only, independent of amount of Objects) and puts the data into repeated_given_time and repeated_given_space)

unique = set(repeated_given_time)

(some other omitted code for calculating and putting some values in the calculated_time_and_space)

time_list = list(unique)
for i in range (len(time_list)):
    print (time_list[i], calculated_time_and_space[i], file = results)

And I have absolutely no idea, how to do these things for multiple Objects in a loop. Obviuosly, I have to create much more of these lists repeated_given_time_N, repeated_given_space_N, calculated_time_and_space_N where N take values from 1 to N = 100 for 100 different Objects.

I know how to create multiple lists, but I couldn't find the efficient method of naming them.

The same thing with creating of multiple .txt's. How can I define their names like Object_N.txt with N from 1 to 100?

It would be great if someone can help me with that.

  • Possible duplicate of [How do I create a variable number of variables?](http://stackoverflow.com/q/1373164/953482). Short answer: when you think you need variables `thing_1`, `thing_2`, ... `thing_n`, use a single list `things` instead. – Kevin Apr 04 '17 at 15:24
  • Yes, this also helped. Ty :) –  Apr 05 '17 at 17:53

1 Answers1

0

If i understand well, you want to create multiple files that differs from one number. If so, you can do something like:

for i in range(10):
    f = open('Object_%s.txt' % i,'w')
    f.write('blabla')
    f.close()

This will create 10 files Objects_N.txt with N from 0 to 9. Else feel free to correct me.

Nuageux
  • 1,668
  • 1
  • 17
  • 29
  • TY very much for the answer. But I still have a problem with accessing these files. They all have the name `f` if I understand it right. How can I access e.g. Only the Object_1.txt? –  Apr 04 '17 at 17:57
  • ...I need it for saving the calculated data there. I would use for it this: `print (, file = f)` and I'm not sure in which .txt the data will land. –  Apr 04 '17 at 18:00
  • 1
    `f` is the current open file. If you need them open all at once, you can create a table of files. `f = [open('Object_%s.txt' % i,'w') for i in range(10)]` This way you can access each one of them with `f[i]` – Nuageux Apr 05 '17 at 12:17