2017-10-10 677 views
0

所以,我有多個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?

+0

如何使用'pandas'並將所有文件讀取爲數據框並將它們全部合併到單個數據框並將其保存到tsv中? –

+0

@SreeramTP從未使用它。我會怎麼做呢? – jskrtsth

回答

0

您可以使用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'

+0

這樣做。謝謝! – jskrtsth

+0

不客氣,很高興幫助! – randomir

相關問題