【问题标题】:Read multiple TSV files and write to one TSV file Python读取多个 TSV 文件并写入一个 TSV 文件 Python
【发布时间】:2017-10-11 03:05:27
【问题描述】:

所以,我有多个 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 的最佳方法是什么?

【问题讨论】:

  • 如何使用pandas 并将所有文件作为数据帧读取并将所有文件连接到单个数据帧并将其保存到 tsv。
  • @SreeramTP 没用过。我该怎么做呢?

标签: python csv parsing


【解决方案1】:

您可以使用标准库中的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 模块读取制表符分隔值文件。

【讨论】:

  • 做到了。谢谢!
猜你喜欢
  • 2023-02-03
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 2023-01-18
  • 1970-01-01
  • 1970-01-01
  • 2014-11-03
  • 1970-01-01
相关资源
最近更新 更多