使用Python逐行从一个文本文件复制到另一个文本文件

时间:2016-05-03 15:25:59

标签: python

我是Python和一般编程的新手,我正在尝试从文本文件(包含字幕)创建一个srt文件

这是我的代码:

  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) 

这就是我得到的:

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 ... 但是,期望的结果是这样的: 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包含:

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

任何帮助将不胜感激:) 谢谢

3 个答案:

答案 0 :(得分:3)

以下是使用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)

将产生以下输出:

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

添加图片以澄清:

enter image description here

答案 1 :(得分:1)

您可以使用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]))

答案 2 :(得分:0)

您的f1.writelines(行)正在循环中发生。因此,每当你绕过循环,你就会写出整个lines

如果不知道in3.txt中的内容,这很难调试。