如何使用python解析tsv文件?

问题描述:

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

I have a tsv file which includes some newline data.

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

此处 b $ c $第三行上的c>是第二行上的 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']