我是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
图片添加了说明:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句