KAMILIA
KAMILIA

Reputation: 39

Copying line by line from one text file to another using Python

I'm new in Python and in programming in general, I'm trying to create an srt file from a text file(that contains the subtitles )

This is the code I have:

  with open("in3.txt") as f:
    lines = f.readlines()
   # lines = [l for l in lines]
    with open("out.txt", "w") as f1:
        for x in range(0, 7):
            y = x*10
            f1.write("\n00:01:"+str(y)+"\n")
            f1.writelines(lines) 

And this is what I get:

00:01:0 This is 1st line This is 2nd line This is 3rd line This is 4th line This is 5th line 00:01:10 This is 1st line This is 2nd line This is 3rd line This is 4th line This is 5th line 00:01:20 This is 1st line This is 2nd line This is 3rd line This is 4th line This is 5th line ... However, the outcome desired is this: 00:01:0 This is 1st line 00:01:10 This is 2nd line 00:01:20 This is 3rd line 00:01:30 This is 4th line

in3.txt contains:

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

Any help will be appreciated :) Thank you

Upvotes: 2

Views: 387

Answers (3)

Abbas
Abbas

Reputation: 4070

Here is solution using enumerate:

with open("in3.txt") as f:
    lines = f.readlines()
    with open("out.txt", "w") as f1:
        for x, line in enumerate(lines): # Changed to enumerate as per recommendation
            y = x*10
            f1.write("\n00:01:"+str(y)+"\n")
            f1.write(line)

will produce following output:

00:01:0
This is 1st line

00:01:10
This is 2nd line

00:01:20
This is 3rd line

00:01:30
This is 4th line

00:01:40
This is 5th line

Image added for clarification:

enter image description here

Upvotes: 3

Farhan.K
Farhan.K

Reputation: 3485

You could use the index of lines:

with open("in3.txt") as f:
    lines = f.readlines()
    with open("out.txt", "w") as f1:
        for x in range(0, 7):
            y = x*10
            f1.write("\n00:01:"+str(y)+"\n")
            f1.write(lines[x]) # Changed f1.writelines(lines) to f1.write(lines[x]))

Upvotes: 1

Louise
Louise

Reputation: 1185

Your f1.writelines(lines) is happening INSIDE the loop. So every time you go round the loop, you're writing the whole of lines.

This is difficult to debug without knowing what's in in3.txt too.

Upvotes: 0

Related Questions