如何以字母数字顺序回写文件中排序后的行

2024-05-23 22:37:24 发布

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

def sortall(string):
    if not string:
        return []
    return (sortall([x for x in string[1:] if x < string[0]])
            + [string[0]] +
            sortall([x for x in string[1:] if x >= string[0]]))


file = open("sorting.txt", "r+")
for line in file.readline():
    xd = (''.join(sortall(line)))
    file2 = open("sorting.txt", "w")
    file2.write(xd)

我如何使它成为我的代码打印排序文件行,但当它这样做时,它会按升序进行


Tags: intxtforstringreturnifdefline
2条回答

这是一种更简洁的方法:

with open('sorting.txt', 'r+') as f:
    sorted_lines = sorted(f.readlines())
    f.writelines(sorted_lines)

正如您在这里看到的:https://docs.python.org/3/howto/sorting.html,您可以提供一个callable来定制排序

sorted(iterable, /, *, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.

A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order.

读取整个文件,排序并写入新文件:

with open('file1', 'r') as f:
    lst = f.readlines()
    with open('file2', 'w') as w:
        w.writelines(sorted(lst))

如果“排序”应该使用一些特殊的排序,请在“key”参数中提供比较函数:

print(help(sorted))

sorted(iterable, /, *, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.

A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order.

相关问题 更多 >