读取多个TSV文件,并写入到一个TSV文件的Python
问题描述:
所以,我有多个TSV文件格式如下:读取多个TSV文件,并写入到一个TSV文件的Python
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)
作为一个侧面说明,你也可以用csv.reader
模块读取制表符分隔值的文件,通过设置dialect='excel-tab'
。
如何使用'pandas'并将所有文件读取为数据框并将它们全部合并到单个数据框并将其保存到tsv中? –
@SreeramTP从未使用它。我会怎么做呢? – jskrtsth