首页 > 解决方案 > 如何在 python 中解析文本文件并打印到另一个文本文件或 json 文件中?

问题描述

我有一个文本文件,它基本上是一个列表,如:

CustomId: 123412412
Name: blah blah

我想逐行解析这个文本文件,并且只打印我最终会指定的我需要的行。现在我可以解析文件并打印它。但是,我在尝试思考将解析并仅打印列表中所需行的逻辑时遇到了麻烦。

标签: pythontext-files

解决方案


def find(search, file_input_path, file_output_path):
  output = open(file_output,"a")
  f = open(file_input_path,'r')
  lines = f.readlines()
  for l in lines:
     if(l == search):
       output.write(s[1]))
  output.close()
  f.close()

使用示例:

find("Name: blah blah", "input.txt", "output.txt")

将在另一个文件中产生如下输出:

Name: blah blah

如果您想查找更多行,只需在循环中调用该函数。


推荐阅读