Reputation: 39
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
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:
Upvotes: 3
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
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