将所有.txt文件合并为一个文本文件,并按字母顺序排列文本文件


Merge all .txt files into one text file and alphabetise that text file

我在一个目录中有两个文件,它们都是.txt文件,每行有一个单词。我需要将它们合并,然后将新文件按字母顺序排列。

我已经在PHP中做到了这一点,但我怎么能在Python 2.7中做到呢?

<?php
$files = glob("./files/*.??");
$out = fopen("listTogether.txt", "w");
foreach($files as $file){
    fwrite($out, file_get_contents($file));
}
fclose($out);
?>

将所有输入文件读入一个列表,对结果进行排序,并再次写出这些行:

from itertools import chain
from glob import glob
lines = list(chain.from_iterable(open(f, 'r') for f in glob('./files/*.??')))
lines.sort()
with open('listTogether.txt', 'w') as out:
    out.writelines(lines)

如果你的文件很大,但是,你想单独排序文件,写出排序的结果,然后合并排序文件到新的输出文件,逐行,使用合并生成器函数。

您似乎正在使用Windows文件,它使用'r'n(回车加换行)行结束符;您可以使用通用换行支持,并以'rU'模式打开文件,以始终给您'n行结尾:

lines = list(chain.from_iterable(open(f, 'rU') for f in glob('./files/*.??')))
lines.sort()
with open('listTogether.txt', 'w') as out:
    out.writelines(lines)

有关U模式字符的详细信息,请参见open()函数调用。

要删除任何重复项,您将创建一个集合而不是一个列表,然后使用sorted()再次写出一个排序的序列:

lines = set(chain.from_iterable(open(f, 'rU') for f in glob('./files/*.??')))
with open('listTogether.txt', 'w') as out:
    out.writelines(sorted(lines))