Concatenation in os.chdir

2
for galaxy in xrange(10):
    for system in xrange(499):
        os.chdir('E:\Scripts')
        os.makedirs(str(galaxy)+'_'+str(system))
        os.chdir('E:\Scripts\%s_%s' % (galaxy, system)
        outfile = open('%s_%s', 'w') % (galaxy, system)
        outfile.write(str(o.galaxy_content(galaxy,system)))
        outfile.close()
        os.chdir('E:\Scripts')

my problem is the following, when I want to do the concatenation% s_% s to create the folder with os.chdir it creates everything well, my problem is when I want to create a .txt with the name% s_% s since it tells me invalid syntax.

    
asked by user2957041 14.05.2017 в 00:00
source

1 answer

1

You are applying the string format on the call of a function, not on a string. It should be outfile = open('%s_%s' % (galaxy, system), 'w') . On the other hand, this way of formatting strings is old, the new style is to use str.format() or even the string literals formatted if you were in Python> = 3.6 (which is not your case):

for galaxy in xrange(10):
    for system in xrange(499):
        os.chdir('E:\Scripts')
        os.makedirs('{}_{}'.format(galaxy, system))
        os.chdir('E:\Scripts\{}_{}'.format(galaxy, system))
        with open('{}_{}'.format(galaxy, system), 'w') as outfile:
            outfile.write(str(o.galaxy_content(galaxy,system)))
        os.chdir('E:\Scripts')

If you wanted to add the .txt extension to each created file, it would be simply:

with open('{}_{}.txt'.format(galaxy, system), 'w') as outfile:

You can see the status documentation with if you want more information about it.

    
answered by 14.05.2017 / 00:20
source