如何使用python解析tsv文件? [英] How to parse tsv file with python?

查看:219
本文介绍了如何使用python解析tsv文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些换行数据的tsv文件。

I have a tsv file which includes some newline data.

111 222 333 "aaa"
444 555 666 "bb
b"

此处 b 是第二行上的 bb 的换行符,因此它们是一个数据:

Here b on the third line is a newline character of bb on the second line, so they are one data:

第一行的第四值:

aaa

第二行的第四值:

bb
b

如果我使用Ctrl + C和Ctrl + V粘贴到excel文件中,则效果很好。但是,如果我想使用python导入文件,该如何解析?

If I use Ctrl+C and Ctrl+V paste to a excel file, it works well. But if I want to import the file using python, how to parse?

我尝试过:

lines = [line.rstrip() for line in open(file.tsv)]
for i in range(len(lines)):
    value = re.split(r'\t', lines[i]))

但结果并不理想:

我要:

推荐答案

只需使用 csv模块。它知道CSV文件中所有可能的极端情况,例如带引号的字段中的新行。

Just use the csv module. It knows about all the possible corner cases in CSV files like new lines in quoted fields. And it can delimit on tabs.

with open("file.tsv") as fd:
    rd = csv.reader(fd, delimiter="\t", quotechar='"')
    for row in rd:
        print(row)

将正确输出:

['111', '222', '333', 'aaa']
['444', '555', '666', 'bb\nb']

这篇关于如何使用python解析tsv文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆