问题
I'm splitting a file based on a string, and would like to have the output file names be numbered.
This is what I have so far:
outputfile = open("output.seq")
outputfileContent = outputfile.read()
outputfileList = outputfileContent.split(">")
for count, line in enumerate(f):
for items in outputfileList:
seqInfoFile = open('%f.dat', 'w')
seqInfoFile.write(str(items))
I'm not sure where to define f.
Thanks for any help!
回答1:
Assuming I haven't misunderstood you, where you have it.
outputfile = open("output.seq")
outputfileContent = outputfile.read()
outputfileList = outputfileContent.split(">")
for count, content in enumerate(outputfileList, 1):
with open("output_%s.dat" % count, "w") as output:
output.write(content)
回答2:
It would seem that if you want to associate every item in the output file list with a file titled as its index, you should do something like this:
for i in range(len(outputfileList)):
seqInfoFile = open(str(i) + '.dat', 'w')
seqInfoFile.write(str(outputfileList[i]))
It's not quite as elegant as an iterator, but the other option is to determine the number by making a call to outputfileList.index(items) each time.
回答3:
Open output.seq
, write its first line (splitted at >
) into the file 1.dat
, the second one to 2.dat
and so on:
with open("output.seq") as fi:
for count, line in enumerate(fi, 1):
with open('{0}.dat'.format(count), 'w') as fo:
fo.writelines(line.split('>'))
来源:https://stackoverflow.com/questions/11651360/iterate-file-name-with-counter