Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...