[英]Reading, editing, and writing over every 4th line in a text file
長時間讀者第一次問問。
我正在編寫一些我需要編輯時間戳的vtt(隱藏式字幕)文件。 該文件的格式如下:
177
00:07:37.450 --> 00:07:39.690
- [Liz] How would you suggest an organization devise
178
00:07:39.690 --> 00:07:41.719
the accountabilities for culture?
179
00:07:41.719 --> 00:07:43.690
- [Tamara] It is a shared accountability
我編寫了以下代碼來讀取文件,計算新的時間戳(慢5%)並吐出新的時間戳:
from sys import argv
script, filename = argv
adjustment = input("Adjustment multiplier: ")
video = open(filename, "r+")
lines = video.readlines()
video.seek(0)
for l in lines:
if l[:2] == "00":
#here I've omitted a lot of calculations to turn the timestamps
#into milliseconds, apply the adjustment multiplier, and turn them back into
#minutes, seconds, and milliseconds.
new_line = str(#concatenation of new values into timestamp format)
video.write(new_line)
video.close()
計算效果很好,但問題是它將所有新行轉儲到文件的開頭,而不是寫入每個時間戳行並跳過其余的。
我很想聽聽你們的想法! 我已經和它搏斗了一段時間並嘗試了很多東西但是還沒能完成它。
謝謝!
您可以嘗試枚舉 ,而迭代的lines
,然后做同樣的過程:
# Reading code here ...
for index, line in enumerate(lines):
if index % 4 == 0:
# Your code here ...
希望它有幫助:)
固定它!
我所要做的就是添加:
else:
video.write(l)
到if語句。 這樣,如果它匹配我的參數,則運行計算並寫入新行,但如果不匹配,則只寫入舊行。
謝謝大家!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.