如何一次读取两个文件,忽略#行,并用第二列值对它们进行排序?
我在考虑组合.startswith():和sorted():command
file1 = [line for line in open("file1.txt",'r').readlines() if not line.startswith("#")]
file2 = [line for line in open("file2.txt",'r').readlines() if not line.startswith("#")]
sorted_file1 = sorted(file1, key=lambda line: int(line.split()[1]))
sorted_file2 = sorted(file2, key=lambda line: int(line.split()[1]))
do something fun using sorted files with for and if
我的文件非常简单。文件1的值类似于
AAA 15125
BBB 69121
CCC 366161
....
和文件2看起来像
bkjnwg 11111
knksng 22155
bnkiop 13511
...
但我对这段代码感到奇怪。如何阅读,忽略#,并更简单地对文件进行排序?
谢谢
最好,
答案 0 :(得分:2)
根据评论编辑。
你可以这样做:
files_to_do = [...] #put paths in here
for f in files_to_do:
lines = [line for line in open(f,'r').readlines() if not line.startswith("#")]
sorted_lines = sorted(lines, key=lambda line: int(line.split()[1]))
#party