简体   繁体   中英

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

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:

在此处输入图片说明

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]))

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM