1

Consider the following MWE.

f_500 = open('halo_classificatio_500_with_surface_pressure_term.txt', 'a')
f_200 = open('halo_classificatio_200_with_surface_pressure_term.txt', 'a')
f_178 = open('halo_classificatio_178_with_surface_pressure_term.txt', 'a')
f_100 = open('halo_classificatio_100_with_surface_pressure_term.txt', 'a')

over_density = [500,200,178,100]
for jj in over_density:
    tm_msun = 2
    cm_msun = 2
    vr_mpc = 2
    file('f_'+str(jj)).write("%s\t%s\t%s\n" % (tm_msun, cm_msun, vr_mpc))

I am getting the following error

IOError: [Errno 2] No such file or directory: 'f_500'

I would like to write to file object f_500 when 'jj' is 500 and so on. What could be the correct way of doing this ?

Thanks

R S John
  • 507
  • 2
  • 9
  • 16

3 Answers3

3

You're defining 4 variables whose values are file type objects on lines 1-4. However, you're not using these variables in your for loop. Instead, in your loop, you're creating more file type objects. (The built-in file() function constructs a file type object with the given name.)

If you really want to open all the files beforehand, you should use a dictionary. The filenames can be constructed using a loop, too:

over_density = [500, 200, 178, 100]
filename_pattern = 'halo_classificatio_%d_with_surface_pressure_term.txt'
files = {}
for d in over_density:
    files[d] = open(filename_pattern % d, 'a')

After that, you can do your for jj loop and access the appropriate file handle with files[jj].

Matthias Wiehl
  • 1,799
  • 16
  • 22
2

Access file variable as key in dict returned by globals() or locals(), depends on context:

locals()['f_'+str(jj)].write("%s\t%s\t%s\n" % (tm_msun, cm_msun, vr_mpc))
globals()['f_'+str(jj)].write("%s\t%s\t%s\n" % (tm_msun, cm_msun, vr_mpc))

Good Luck ! :)

Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
0

This is what you need be doing in the last statement :

exec('''f_%s.write("%s\t%s\t%s\n" % (tm_msun, cm_msun, vr_mpc))''' % (str(jj)) )
harshil9968
  • 3,254
  • 1
  • 16
  • 26