Skip to main content
 首页 » 编程设计

python之如何使用分隔符将 csv 文件拆分为多个文件 Python

2024年10月25日6kuangbin

我有一个制表符分隔的文件:

这是一个句子。 abb 这是什么 foo 栏。贝弗 你好 foo bar blah 黑羊。 abb

我可以在 unix 终端中使用 cut -f1 和 cut -f2 拆分成两个文件:

this is a sentence. 
what is this foo bar. 
hello foo bar blah black sheep. 

和:

abb 
bev 
abb 

但是在 python 中可以做同样的事情吗?会更快吗?

我一直这样做:

[i.split('\t')[0] for i in open('in.txt', 'r')] 

请您参考如下方法:

But is it possible to do the same in python?

是的,你可以:

l1, l2 = [[],[]] 
 
with open('in.txt', 'r') as f: 
    for i in f: 
        # will loudly fail if more than two columns on a line 
        left, right = i.split('\t') 
        l1.append(left) 
        l2.append(right) 
 
print("\n".join(l1)) 
print("\n".join(l2)) 

would it be faster?

不太可能,cut 是一个针对这种处理进行了优化的 C 程序,python 是一种通用语言,具有很大的灵 active ,但不一定很快。

不过,使用像我编写的算法这样的算法可能获得的唯一优势是您只读取文件一次,而使用 cut 时,您读取文件两次。这可能会有所作为。

虽然我们需要运行一些基准测试才能达到 100%。

这是一个小的基准测试,在我的笔记本电脑上,它的值(value):

>>> timeit.timeit(stmt=lambda: t("file_of_606251_lines"), number=1) 
1.393364901014138 

对比

% time cut -d' ' -f1 file_of_606251_lines > /dev/null 
cut -d' ' -f1 file_of_606251_lines > /dev/null  0.74s user 0.02s system 98% cpu 0.775 total 
% time cut -d' ' -f2 file_of_606251_lines > /dev/null 
cut -d' ' -f2 file_of_606251_lines > /dev/null  1.18s user 0.02s system 99% cpu 1.215 total 

即 1.990 秒。

所以 python 版本确实更快,正如预期的那样 ;-)