2017-09-05 86 views
1

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

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

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

回答

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 
0

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

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)) 
相关问题