Python3:如何循环遍历文本文件并找到匹配的关键字?

2024-09-28 03:23:12 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,我是一个完全的编码新手,不知道自己在做什么

我正在使用一个数据库txt文件,并已将其导入并打开。我现在需要遍历文件,找到一个特定的关键字(数字),并将其打印到一个新文件中。我一直在试图理解编码,但毫无结果。有人能给我解释一下怎么做吗。请低声解释,让我这样的白痴明白

 file1 = open('database.txt', 'r')
 Lines = file1.readlines()

pattern = "gene_numbers_here"

for line in Lines:
   
  
   if pattern in line:
      print(..., file = open("gene1found.txt",'w'))```
  

Tags: 文件intxt数据库编码line数字关键字
1条回答
网友
1楼 · 发布于 2024-09-28 03:23:12

使用readlines将txt文件逐行加载到字符串列表中

file1 = open('myfile.txt', 'r')
Lines = file1.readlines()

现在是循环:

for line in Lines:
   print(line)

基于您的问题,您实际上希望在字符串中执行“模式搜索”。 为此,只需使用循环示例中的相同代码并插入“模式搜索”函数,逐行检查txt文件中是否存在您的模式

# declare the pattern
pattern = "this_pattern_only"

# loop through the list of strings in Lines
for line in Lines:
   
   # patter search statement
   if pattern in line:
      print("pattern exist")
   else:
      print("pattern does not exist")

如果要将其打印到文件中,只需更改我制作的打印代码行。
在此处查看有关写入功能的更多信息:
https://www.w3schools.com/python/python_file_write.asp

根据有关代码的新信息,尝试以下操作:

# file1 is database, file2 is output
file1 = open('database.txt', 'r')
file2 = open('gene1found.txt', 'w')

Lines = file1.readlines()
pattern = "gene_numbers_here"


# search and write lines with gene pattern
print("Searching database ...")

for line in Lines:  
   if pattern in line:
      file2.write(line)

print("Search complete !")


# close the file
file1.close()
file2.close()

这将用你想要的模式写入你的文件

相关问题 更多 >

    热门问题