【发布时间】:2021-12-03 06:17:54
【问题描述】:
我有一个我之前使用过的脚本,它使用关键字列表来查询具有多个列和条目的主文件。该脚本应逐行读取主文件,当遇到关键字时,会将整行写入新文件。
关键字文件如下所示:
A2M,ABCC9,ACADVL,ACTC1,ACTN2,ADA2,AGL
主文件如下所示:
8:27379821,8,27379821,[A/T],NM_001979,NM_001256482,NM_001256483,NM_001256484,A2M,A2M,A2M,A2M,,Silent,Silent,Silent,Silent
GSA-rs72475893,8,27380763,[A/G],NM_001979,NM_001256482,NM_001256483,NM_001256484,AM,AM,AM,AM,EXON,Missense_R1407W,Missense_R1307W,Missense_R1257W,Missense_R1407W
8:27381207,8,27381207,[A/C],NM_001979,NM_001256482,NM_001256483,NM_001256484,ADA2,ADA2,ADA2,ADA2,,Silent,Silent,Silent,Silent
GSA-rs117056676,6,72385948,[T/C],,,,,AADACL2-AS1,AADAC,EXON,Silent,Silent,Missense_X400Q
所需的输出将是:
8:27379821,8,27379821,[A/T],NM_001979,NM_001256482,NM_001256483,NM_001256484,A2M,A2M,A2M,A2M,,Silent,Silent,Silent,Silent
8:27381207,8,27381207,[A/C],NM_001979,NM_001256482,NM_001256483,NM_001256484,ADA2,ADA2,ADA2,ADA2,,Silent,Silent,Silent,Silent
我正在使用的代码如下。我遇到的问题是“匹配”列表变量似乎是空的,它没有附加任何东西。为什么会这样?它没有进行任何匹配吗?还是因为它没有将它们附加到列表中?
我尝试将主文件和关键字文件用作 .csv 和 .txt,但没有任何效果。
感谢您的帮助!
#open the list of words to search for
list_file = open(r'file.csv','r')
search_words = []
#loop through the words in the search list
for word in list_file:
#save each word in an array and strip whitespace
search_words.append(word.strip())
list_file.close()
#this is where the matching lines will be stored
matches = []
#open the master file
master_file = open(r'file2.csv','r')
#loop through each line in the master file
for line in master_file:
#split the current line into array, this allows for us to use the "in" operator to search for exact strings
current_line = line.split()
#loop through each search word
for search_word in search_words:
#check if the search word is in the current line
if search_word in current_line:
#if found then save the line as we found it in the file
matches.append(line)
#once found then stop searching the current line
break
master_file.close()
#create the new file
new_file = open(r'file3.txt', 'w')
#loop through all of the matched lines
for line in matches:
#write the current matched line to the new file
new_file.write(line)
new_file.close()
【问题讨论】:
-
.split()默认情况下用空格分隔字符串(您的文件中似乎不存在),not 逗号。 -
简单调试会发现
current_line可能不包含您认为的内容。 How to debug small programs -
@jasonharper 谢谢!这似乎解决了它。
-
@Woodford 线实际上运行良好,一直迭代到最后。对未来来说仍然是一个非常有用的资源,谢谢!
标签: python matching file-writing