因此,我有多个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,.))( is标题)
我想全部读取它们,如果对于每一行列都有我想要的属性(假设它等于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的最佳方法是什么?
发布于 2017-10-10 18:59:16
您可以使用标准库中的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)另外,您还可以使用csv.reader模块通过设置dialect='excel-tab'读取选项卡分隔的值文件.
https://stackoverflow.com/questions/46673801
复制相似问题