jon_shep
jon_shep

Reputation: 1463

Python - Producing custom filename during creation

So I have a script that produces files named for each key in a dictionary. (script below)

 for key, values in sequencelist.items():
     with open(key, 'w') as out:
         for value in values:
             out.write('\n'.join(value.split()) + '\n')

Can someone help me modify the above syntax to do more? I would like to append some plain text onto the filename as well as add the current len(dict.keys()) using range() See my script below, which doesn't work! :)

for key, values in sequencelist.items():
    for i in range(len(sequencelist.keys())):
        j = i+1
        with open('OTU(%j)' +'_' + key +'.txt' %j, 'w') as out:
            for value in values:
                out.write('\n'.join(value.split()) + '\n')

So this the first file created would be OTU(1)_key.txt

I am sure the with open() line is 100% wrong.

Could someone also link me stuff to read on the use of %j to call the variable j from the line before works? I was trying to use code from this Overflow answer (Input a text file and write multiple output files in Python) with no explanation.

Upvotes: 1

Views: 2821

Answers (1)

Pyrce
Pyrce

Reputation: 8571

Try the following

for count, (key, values) in enumerate(sequencelist.items()):
    with open('OTU(%d)_%s.txt' % (count+1, str(key)), 'w') as out:
        for value in values:
            out.write('\n'.join(value.split()) + '\n')

I swapped the ordering of your open call with your value iteration so you don't get len(sequencelist) files for each value. It seemed like your j argument was not required after this change. The enumerate call makes the count part of the for loop increment each time the loop repeats (it doesn't have to be called count).

The %d asks for an integer, the %s for a string, which depending on the key name will convert nicely with str(). If your key is some custom class you'll want to convert it to a nicer string format as you'll get someting like <class __main__.Test at 0x00000....>.

Upvotes: 1

Related Questions