[英]Read multiple TSV files and write to one TSV file 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
模塊讀取制表符分隔值的文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.