要按时间排序一个包含时间信息的txt文件中的行,可以使用以下步骤进行解决:
lines = []
with open("按时间排序.txt", "r") as file:
for line in file:
lines.append(line.strip())
sorted()
函数,并自定义一个比较函数,比较函数需要将时间字符串转换为datetime
对象进行比较。from datetime import datetime
def compare_time(line):
time_str = line.split(": ")[1] # 假设时间信息的格式为"时间: xxx"
time_obj = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")
return time_obj
sorted_lines = sorted(lines, key=compare_time)
with open("按时间排序.txt", "w") as file:
for line in sorted_lines:
file.write(line + "\n")
完整代码示例:
from datetime import datetime
def compare_time(line):
time_str = line.split(": ")[1] # 假设时间信息的格式为"时间: xxx"
time_obj = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")
return time_obj
lines = []
with open("按时间排序.txt", "r") as file:
for line in file:
lines.append(line.strip())
sorted_lines = sorted(lines, key=compare_time)
with open("按时间排序.txt", "w") as file:
for line in sorted_lines:
file.write(line + "\n")
注意:以上代码示例假设时间信息的格式为"时间: xxx",需要根据实际情况进行调整。另外,如果txt文件较大,可能会导致内存占用较高,可以考虑使用其他方法进行处理,如分批读取和排序。
上一篇:按时间浏览页面