python - Write output of for loop to multiple files -


i trying read each line of txt file , print out each line in different file. suppose, have file text this:

how you? good. wow, that's great. text file. ...... 

now, want filename1.txt have following content:

how you? good. 

filename2.txt have:

wow, that's great. 

and on.

my code is:

#! /usr/bin/python  in range(1,4): // range should increase number of lines     open('testdata.txt', 'r') input:        open('filename%i.txt' %i, 'w') output:           line in input:             output.write(line) 

what getting is, files having lines of file. want each file have 1 line, explained above.

move 2nd with statement inside loop , instead of using outside loop count number of lines, use enumerate function returns value , index:

with open('testdata.txt', 'r') input:   index, line in enumerate(input):       open('filename{}.txt'.format(index), 'w') output:           output.write(line) 

also, use of format typically preferred % string formatting syntax.


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -