Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write output of for loop to multiple files

I am trying to read each line of a txt file and print out each line in a different file. Suppose, I have a file with text like this:

How are you? I am good.
Wow, that's great.
This is a text file.
......

Now, I want filename1.txt to have the following content:

How are you? I am good.

filename2.txt to have:

Wow, that's great.

and so on.

My code is:

#! /usr/bin/Python

for i in range(1,4): // this range should increase with number of lines 
   with open('testdata.txt', 'r') as input:
       with open('filename%i.txt' %i, 'w') as output:
          for line in input:
            output.write(line)

What I am getting is, all the files are having all the lines of the file. I want each file to have only 1 line, as explained above.

like image 615
user2481422 Avatar asked Sep 05 '25 17:09

user2481422


2 Answers

Move the 2nd with statement inside your for loop and instead of using an outside for loop to count the number of lines, use the enumerate function which returns a value AND its index:

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

Also, the use of format is typically preferred to the % string formatting syntax.

like image 163
BeetDemGuise Avatar answered Sep 07 '25 11:09

BeetDemGuise


Here is a great answer, for how to get a counter from a line reader. Generally, you need one loop for creating files and reading each line instead of an outer loop creating files and an inner loop reading lines.

Solution below.

#! /usr/bin/Python

with open('testdata.txt', 'r') as input:
    for (counter,line) in enumerate(input):
        with open('filename{0}.txt'.format(counter), 'w') as output:
            output.write(line)
like image 30
M. K. Hunter Avatar answered Sep 07 '25 10:09

M. K. Hunter