python - 如何逐行对文本文件进行排序

标签 python python-3.x file sorting

我需要按升序对文本文件进行排序。文本文件的每一行都以一个索引开头,如下所示:

2       0       4         0d 07:00:38.0400009155273
3       0       4         0d 07:00:38.0400009155273
1       0       4         0d 07:00:38.0400009155273   

想法结果如下:

1       0       4         0d 07:00:38.0400009155273
2       0       4         0d 07:00:38.0400009155273
3       0       4         0d 07:00:38.0400009155273 

请注意,此文本文件有超过 300 万行,每个元素自然被视为一个字符串。

我已经弄乱这个问题一段时间了,但没有任何运气,所以我认为是时候咨询专家了。谢谢你的时间!

编辑:

我在 Spyder IDE 中使用带有 Python 3.7 的 Windows 操作系统。该文件不是 CSV,而是制表符分隔的文本文件。有可能并非所有指数都存在。原谅菜鸟,我没有很多编码经验。

最佳答案

fn = 'filename.txt'
sorted_fn = 'sorted_filename.txt'

with open(fn,'r') as first_file:
    rows = first_file.readlines()
    sorted_rows = sorted(rows, key=lambda x: int(x.split()[0]), reverse=False)
    with open(sorted_fn,'w') as second_file:
        for row in sorted_rows:
            second_file.write(row)

这应该适用于 3+ 百万行的文本文件。使用 int(x.split()[0]) 将每行中的第一项排序为整数

编辑以删除 close() 语句

关于python - 如何逐行对文本文件进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56120633/

相关文章:

php - 如何使用 Unlink() 函数

使用c在linux中创建具有给定名称和权限的文件

python - pybind11 与 numpy 的矩阵乘积

python - 从文本文件中删除单个值

Python Flask - 如何使用 SubmitField 删除对象?

python - 用双引号Python获取str repr

python - 如何在 Python 3 中根据字符串参数捕获一般异常?

正确使用 Stat on C

python - pandas dataframe切片产生不同的结果

Python-tkinter组合框保存值