我有两个文件。
一个文件有两列,我们称之为db
,另一个文件有一列,我们称之为in
。db
中的第二列与in
中的列类型相同,两个文件都按此列排序。
db例如:
RPL24P3 NG_002525
RPLP1P1 NG_002526
RPL26P4 NG_002527
VN2R11P NG_006060
VN2R12P NG_006061
VN2R13P NG_006062
VN2R14P NG_006063
例如:
NG_002527
NG_006062
我希望通读这些文件并获得如下输出:
NG_002527: RPL26P4
NG_006062: VN2R13P
这意味着我在in
行上迭代,并试图在db
中找到匹配的行。
我为此编写的代码是:
with open(db_file, 'r') as db, open(sortIn, 'r') as inF, open(out_file, 'w') as outF:
for line in inF:
for dbline in db:
if len(dbline) > 1:
dbline = dbline.split('\t')
if line.rstrip('\n') == dbline[db_specifications[0]]:
outF.write(dbline[db_specifications[0]] + ': ' + dbline[db_specifications[1]] + '\n')
break
*db_specification
与此问题无关,因此我没有为其复制相关代码-问题不在那里
当前代码将找到一个匹配项,并按照我在in
中为第一行计划的那样编写它,但不会为其他行找到任何匹配项。我怀疑这与break
有关,但我不知道该改变什么
我可以通过插入以下行来解决问题:
line = next(inF)
在break语句之前由于db_文件中的数据按第二列排序,因此可以使用此代码读取该文件
输出文件将包含以下项:
在上面的代码中,我们必须先阅读排序列表。然后读取db_文件中的每一行。i_list[-1]将具有sortIn file的最大值,因为sortIn文件也按升序排序
与下面的代码相比,上面的代码具有更少的i/o
=========== 以前提交的答复:
根据数据在db_文件中的存储方式,我们似乎必须读取整个文件,以对照sortIn文件进行检查。如果db_文件中的值按第二列排序,那么一旦找到sortIn中的最后一项,我们就可以停止读取该文件
假设我们需要从文件中读取所有记录,看看下面的代码是否适合您
输出文件将包含以下项:
为了帮助您,我还打印了d_列表、i_列表和out_列表中的内容
d_列表中的内容如下所示:
i_列表中的内容如下所示:
从out_列表写入out文件的内容如下所示:
相关问题 更多 >
编程相关推荐