我有一个文本文件,如下所示:
A B C D E
1 1 2 1 1e8
2 1 2 3 1e5
3 2 3 2 2000
50 2 3 2 2000
80 2 3 2 2000
...
1 2 5 6 1000
4 2 4 3 1e4
50 3 6 4 5000
120 3 5 2 2000
...
2 3 2 3 5000
3 3 4 5 1e9
4 3 2 3 1e6
7 3 2 3 43
...
我需要一个代码来浏览此文本文件,并在第一列中提取具有相同编号的行[A],并保存在不同的文件中,
例如第一列= 1和...
1 1 2 1 1e8
1 2 5 6 1000
我用while循环编写了代码,但是问题是这个文件很大,并且使用while循环可以处理文本中不存在的数字,并且需要很长时间才能完成,
感谢您的帮助
答案 0 :(得分:0)
以下两个示例都将覆盖运行路径中名为input_<number>.txt
的文件。
awk
rm input_[0-9]*.txt; awk '/^[0-9]+[ \t]+/{ print >> "input_"$1".txt" }' input.txt
前部分/^[0-9]+[ \t]+/
进行正则表达式匹配,以仅选择以整数开头的行,第二部分{ print >> "input_"$1".txt" }
将这些行打印到名为input_<number>.txt
的文件中,文件第一列中找到的每个数字都包含一行。
import sys
import os
fn = sys.argv[1]
name, ext = os.path.splitext(fn)
with open(fn, 'r') as f:
d = {}
for line in f:
ind = line.split()[0]
try:
ind = int(int)
except ValueError:
continue
try:
d[ind].write(line)
except KeyError:
d[ind] = open(name + "_{}".format(ind) + ext, "w")
d[ind].write(line)
for dd in d.values():
dd.close()
在这种情况下,您必须先删除所有旧的输出文件,然后才能使用rm input_[0-9]*.txt
import sys
import os
fn = sys.argv[1]
name, ext = os.path.splitext(fn)
with open(fn, 'r') as f:
for line in f:
ind = line.split()[0]
try:
ind = int(int)
except ValueError:
continue
with open(name + "_{}".format(ind) + ext, "a") as d:
d.write(line)
如果您在计算机上比较精明,可以按照this answer使用ulimit -n <number>
来增加进程的打开文件句柄的限制。