使用python按时间戳对文本文件行排序

2024-09-27 00:17:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个txt文件,其中第1-5行都是单词,第6行及以上的开头有timestamp,如图所示:

This is a document1
This is a document2
This is a document3
This is a document4
This is a document5
2019-05-27 07:00:00, value1, value2, value3
2019-05-27 06:38:00, value1, value2, value3
2019-05-27 07:05:00, value1, value2, value3

如何将第6行排序到最早时间在上面,最晚时间在下面的最后一行?你知道吗

这是我试图基于另一个堆栈溢出问题,但没有工作。你知道吗

  lines = sorted(open(outputFile.txt).readlines(), key=lambda line: line[5:-1].split(",")[0])
  outFile.close()

Tags: 文件txtisline时间this单词timestamp
3条回答

如果您不“需要”单行线,可以执行以下操作:

# Read all lines
with open("file.txt") as f:
    lines = f.readlines()

# Keep only from 6th line
lines = lines[5:]
# Sort based on the date of each line
lines.sort(key = lambda l : l.split(',')[0])

未经测试,但应该有效。你知道吗

您可以将文件读取为pandas DataFrame,然后在相应的行上使用sort_values()。你知道吗

另外,我建议将列强制转换为它们的类型,并将表转换为整洁的格式->;这里第一列应该仅为datetime

使用这种方法,您基本上有两条生产线(不带铸造):

df = read_csv('name_of_file.txt', sep='\t', skiprows=5, header=None, names=['first_col'])
df.sort_values('first_col', ascending=True)

这里(in1.txt是来自post的数据)

from datetime import datetime

with open('in1.txt') as f:
    sorted_lines = sorted([l.strip() for l in f.readlines()][5:],
                          key=lambda line: datetime.strptime(line.split(",")[0], "%Y-%m-%d %H:%M:%S"))
    for line in sorted_lines:
        print(line)

输出

2019-05-27 06:38:00, value1, value2, value3
2019-05-27 07:00:00, value1, value2, value3
2019-05-27 07:05:00, value1, value2, value3

相关问题 更多 >

    热门问题