Dja*_*son 0 php python sorting file-io python-2.7
我在目录中有两个文件,它们都是.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);
?>
Run Code Online (Sandbox Code Playgroud)
将所有输入文件读入一个列表,对结果进行排序并再次写出行:
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)
Run Code Online (Sandbox Code Playgroud)
但是,如果文件很大,则需要单独对文件进行排序,写出排序结果,然后使用合并生成器函数将排序后的文件逐行合并到新的输出文件中.
您似乎正在使用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)
Run Code Online (Sandbox Code Playgroud)
有关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))
Run Code Online (Sandbox Code Playgroud)