0

I have a file say Test.py, I am importing this Test.py into another main.py. now considering that all the lines in Test.py as string, how can I search for a substring in Test.py by writing the required code in main.py

Chandrika
  • 1
  • 1
  • 1
    Do you need to import Test.py? That executes code, if not, Test.py can be read like any other text file. Otherwise see the `inspect` module. – JonSG May 18 '21 at 12:57
  • @JonSG how can I read lines from Test.py. can u please explain – Chandrika May 18 '21 at 13:03
  • check out: https://stackoverflow.com/questions/53204752/how-do-i-read-a-text-file-as-a-string – JonSG May 18 '21 at 13:07

1 Answers1

0

Does this help? You would be better off reading from a .txt file than parsing a .py file.

#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) 
ItsDr4g0n
  • 46
  • 1
  • @ItsDr0n But my aim is to read it using a .py file – Chandrika May 18 '21 at 14:29
  • @Chandrika, can you send what the content of the Test.py file would look like and I may have a solution but I'm not sure if you can read directly from the Test.py file. – ItsDr4g0n May 19 '21 at 15:16