python - 如何在给定文件的给定行号处附加时间?

标签 python python-3.x

我想通过检查文本文件中的行数在文本前面的每一行中写入时间,因为我想按照此链接将此文本文件转换为 .srt 文件。 https://unix.stackexchange.com/questions/111024/how-to-convert-a-txt-subtitle-file-to-srt-format

每一行都是 1 秒。(从 00:00:00 开始第一行:) 我的文件有很多行(500-1000 行) 来自

.......Text......... (first line)
.......Text......... (second line)
.......Text......... (third line)
    .
    .
    .
.......Text......... (60 line)
.......Text......... (61 line)
    .
    .
.................... (3600 line)

到此

00:00:01:.......Text......... (first line)
00:00:02:.......Text......... (second line)
00:00:03:.......Text......... (third line)
    .
    .
    .
00:01:00:.......Text......... (60 line)
00:01:01:.......Text......... (61 line)
    .
    .
01:00:00:.................... (3600 line)

我想检查行号并在每行前面写入文本, 但我的代码中有一个逻辑错误来检查行号并打开文件在该行写入文本。 我不知道如何编写 for 循环并比较行数。我对这个很菜鸟。

def numberline(fname):
    with open(fname) as f:
           for i, l in enumerate(f):
                  pass
    return i + 1
numberline("/home/pi/gtest.txt")) 

dataFile = open("/home/pi/gtest.txt", "w")
    for line in range(numberline("/home/pi/gtest.txt")):
dataFile.write("00:00:%02d:\n" % line)
    dataFile.close()

最佳答案

试试这个(假设 a.txt 是一个包含多行的文本文件)

import datetime


def make_time(num_of_seconds):
    hours = 0 if num_of_seconds < 3600 else num_of_seconds / 3600
    minutes = 0 if num_of_seconds < 60 else (num_of_seconds - hours * 3600) / 60
    seconds = num_of_seconds - (minutes * 60) - (hours * 3600)
    t = datetime.time(hours,minutes,seconds)
    return t.strftime("%H:%M:%S")


new_lines = []
with open('a.txt', 'r') as f_in:
    lines = f_in.readlines()
for idx, line in enumerate(lines):
    new_lines.append('{}:{}'.format(make_time(idx), line))
for l in new_lines:
    print(l.strip())

关于python - 如何在给定文件的给定行号处附加时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55169603/

相关文章:

Python - 找到最近的时间戳

Django-paypal:带有无效回传的 IPN 请求

python - 通过传递坐标来位击棋盘上的白色方 block

python - 面临属性错误: for 'tag_' using Spacy in Python

python - HTTP POST 响应是如何构造的?我如何用 Python 和 urllib2 重新创建它们来模拟填写表单?

python - 颜色条刻度标签作为日志输出

python - 通过 Python 返回 JSON 数组中的值和数据

python - 我可以使用该类的对象访问类变量吗

python - 如何获取Python/Pip包的PyPi链接、许可证、代码和主页?

python-3.x - 如何在 Cython 中使用 memcpy