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.
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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.