【问题标题】:How to search for a string in another python script [duplicate]如何在另一个python脚本中搜索字符串[重复]
【发布时间】:2021-08-07 17:06:47
【问题描述】:

我有一个文件 Test.py,我正在将这个 Test.py 导入另一个 main.py。现在考虑到 Test.py 中的所有行都是字符串,我如何通过在 main.py 中编写所需的代码来搜索 Test.py 中的子字符串

【问题讨论】:

  • 需要导入Test.py吗?执行代码,如果没有,Test.py 可以像任何其他文本文件一样读取。否则请参阅inspect 模块。
  • @JonSG 如何从 Test.py 中读取行。你能解释一下吗

标签: python python-3.x python-2.7 python-requests python-import


【解决方案1】:

这有帮助吗?你最好从 .txt 文件中读取而不是解析 .py 文件。

#You can just use a text file and use the .find() method
#You can import the text file using an import statement
from folder_name import text_file
#Read from text file
substring = "foo"
with open(text_file, "r") as f:
  # Read file
  content = f.read()
  # Check to see if the substring is found in the text file
  if (substring in content):
    # Prints location in char of the first instance of this substring
    print(content.find(substring) 

【讨论】:

  • @ItsDr0n 但我的目标是使用 .py 文件读取它
  • @Chandrika,您能否发送 Test.py 文件的内容,我可能有一个解决方案,但我不确定您是否可以直接从 Test.py 文件中读取。
猜你喜欢
  • 2012-03-05
  • 1970-01-01
  • 2013-09-25
  • 2021-11-28
  • 1970-01-01
  • 2015-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多