4

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.

user2481422
  • 868
  • 3
  • 17
  • 31

2 Answers2

11

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.

BeetDemGuise
  • 954
  • 7
  • 11
2

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)
Community
  • 1
  • 1
M. K. Hunter
  • 1,778
  • 3
  • 21
  • 27