[英]Copying line by line from one text file to another using 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
任何帮助将不胜感激:)谢谢
这是使用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
图片添加了说明:
您可以使用以下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]))
您的f1.writelines(lines)正在循环内发生。 因此,每次循环时,您都在写整lines
。
如果不知道in3.txt
的内容,则很难调试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.