打开文本文件,对文本文件进行排序,然后使用Python

时间:2017-09-05 14:42:25

标签: python-3.x

我从Stackoverflow找到了以下Python代码,它打开了一个名为sort.txt的文件,然后对文件中包含的数字进行排序。

代码非常完美。我想知道如何将已排序的数据保存到另一个文本文件。每次我尝试时,保存的文件都显示为空。 任何帮助,将不胜感激。 我希望将保存的文件称为sorted.txt

with open('sort.txt', 'r') as f:
    lines = f.readlines()
numbers = [int(e.strip()) for e in lines]
numbers.sort()

3 个答案:

答案 0 :(得分:0)

您可以将其与f.write()

一起使用
with open('sort.txt', 'r') as f:
    lines = f.readlines()
numbers = [int(e.strip()) for e in lines]
numbers.sort()

with open('sorted.txt', 'w') as f: # open sorted.txt for writing 'w'
    # join numbers with newline '\n' then write them on 'sorted.txt'
    f.write('\n'.join(str(n) for n in numbers))

测试用例:

sort.txt

1
-5
46
11
133
-54
8
0
13
10

sorted.txt在运行程序之前,它不存在,运行后,它已创建并将已排序的数字作为内容:

-54
-5
0
1
8
10
11
13
46
133

答案 1 :(得分:0)

从当前文件中获取已排序的数据并保存到变量中。 以写入模式('w')打开新文件,并将已保存变量中的数据写入文件。

答案 2 :(得分:0)

使用<file object>.writelines()方法:

with open('sort.txt', 'r') as f, open('output.txt', 'w') as out:
    lines = f.readlines()
    numbers = sorted(int(n) for n in lines)
    out.writelines(map(lambda n: str(n)+'\n', numbers))
相关问题