读取多个 TSV 文件并写入一个 TSV 文件 Python



所以,我有多个具有以下格式的 TSV 文件:

a    b    c    d    e    f    g    h
a_1  b_1  c_1  d_1  e_1  f_1  g_1  h_1
a_2  b_2  c_2  d_2  e_2  f_2  g_2  h_2
.    .    .    .    .    .    .    .
.    .    .    .    .    .    .    .
.    .    .    .    .    .    .    .
a_n  b_n  c_n  d_n  e_n  f_n  g_n  h_n

第一行(a,b,...)是标题)

我想

全部读取它们,如果对于每一行,其中一列具有我想要的属性(假设它等于 1),我想将该行保存在与上述格式相同的不同 TSV 文件中,但数据将被过滤。

有代码来提取我想要的行并将其写入 TSV 文件,但我不确定如何读取多个 TSV 文件并写入单个 TSV 文件。

这是我到目前为止所拥有的:

with open("./someDirectory/file.tsv") as in_file, 
open("newFile.tsv","w") as out_file:
first_line = True
for line in in_file:
    if first_line: #to print the titles
        print(line, file=out_file)
        first_line = False
    columns = line.split("t")
    columnToLookAt = columns[7]
    if columnToLookAt == "1":
        print(line, file=out_file)

所以说someDirectory有80个tsv文件。遍历所有这些并编写所需的行以out_file的最佳方法是什么?

您可以使用标准库中的glob.glob根据某种模式获取文件名列表:

>>> import glob
>>> glob.glob('/tmp/*.tsv')
['/tmp/file1.tsv', '/tmp/file2.tsv', ...]

然后遍历所有这些作为输入文件。例如:

import glob
first_line = True
with open("newFile.tsv","w") as out_file:
    for in_path in glob.glob("./someDirectory/*.tsv"):
        with open(in_path) as in_file:
            for line in in_file:
                if first_line: #to print the titles
                    print(line, file=out_file)
                    first_line = False
                columns = line.split("t")
                columnToLookAt = columns[7]
                if columnToLookAt == "1":
                    print(line, file=out_file)

作为旁注,您还可以通过设置 dialect='excel-tab' 来使用csv.reader模块读取制表符分隔值文件。

最新更新