I love Code
I love Code

Reputation: 101

Read a file and Write on another

I made a script which reads each line of a file and I need those lines on another file but all the script does is writing only one line. How do I make this out?

I tried to loop the read lines and each loop it would write them on the other file

with open('text.txt') as f:
   for line in f:
       print line

       file = open('testfile.txt', 'w')
       file.write(line)

       if 'str' in line:
          break

Upvotes: 1

Views: 69

Answers (3)

Egrzeda
Egrzeda

Reputation: 1

Move the opening line outside of the loop. When the opening line is in the loop, it creates a new file over and over, writing a single line to that file before deleting it to create a new one at the beginning of each loop iteration. When you move the opening line outside the loop, the file is only created once, writing each line to that one file instead of overwriting the whole file each time.

Upvotes: 0

Keijack
Keijack

Reputation: 868

I think you should always close the file, so the file that you open to write should also use with

with open("test.txt") as f, open("testfile.txt", "w") as f2:
    for line in f:
        f2.write(line)
        if 'str' in line:
            break

Upvotes: 4

U13-Forward
U13-Forward

Reputation: 71580

Try this:

with open('text.txt') as f:
   file = open('testfile.txt', 'w')
   for line in f:
       print line
       file.write(line)
       if 'str' in line:
          break

Create the text file outside of the loop will work.

Upvotes: 3

Related Questions