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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.