Looping a write command to output many different indices from a list separately in Python -


im trying output like:

kplr003222854-2009131105131 

in text file. way attempting derive output such:

with open('processed_data.txt', 'r') file_p, open('kic_list.txt', 'w') namelist:     namedata = []                line in file_p:         splt_file_p = line.split()         namedata.append(splt_file_p[0])     key in namedata:         namelist.write('\n' 'kplr00' + "".join(str(w) w in namedata) + '-2009131105131') 

however having issue in numbers in namedata array appearing @ once in specified output, instead of using on id cleanly shown above output this:

kplr00322285472138721382172198371823798123781923781237819237894676472634973256279234987-2009131105131 

so question how loop write command in way allow me each separate id (each has specific index value, there on 150) outputted.

edit: also, of id's in list not same length, wanted add 0's front of 'key' make them equal 9 digits. cheated adding 0's kplr in quotes not of id's need 2 0's. question is, add 0's between kplr , key in way match 9-digit format?

your code looks it's working 1 expect: "".join(str(w) w in namedata) makes string composed of concatenation of every item in namedata.

chances want;

for key in namedata:     namelist.write('\n' 'kplr00' + key + '-2009131105131') 

or better:

for key in namedata:     namelist.write('\nkplr%09i-2009131105131'%int(key)) #no string concatenation 

string concatenation tends slower, , if you're not operating on strings, involve explicit calls str. here's pair of ideone snippets showing difference: http://ideone.com/rr5rnl , http://ideone.com/vh2gzx

also, above form format string '%09i' pad 0s make number 9 digits. because format '%i', i've added explicit conversion int. see here full details: http://docs.python.org/2/library/stdtypes.html#string-formatting-operations

finally, here's single line version (excepting with statement, should of course keep):

namelist.write("\n".join("kplr%09i-2009131105131"%int(line.split()[0]) line in file_p)) 

Comments