-1

I want to make the print({}) display something from another File. What I have been trying:

main.py:

with open("Filename.txt", "tr") as f:
  data = f.readlines()
 if "print({})" in data:
  print("{}".format(data))

Filename.txt:

print("Hello world")

result:

This means I have made an error. But there were no error messages. What did I do wrong?

CodeShed
  • 13
  • 3
  • The file doesn't contain the exact string `print({})`, so the `if` statement isn't entered. It isn't clear what you want it to do instead. – interjay Sep 19 '21 at 14:54
  • `if "print({})" in data:` doesn't do what you think it does. You are clearly expecting it to match any call to the `print()` function. But `in` doesn't do that. I think you are reaching for a regular expression match. Look at the `re` module, specifically `re.search()`. Be aware that for beginners `re`'s learning curve is a bit steep. – BoarGules Sep 19 '21 at 15:14

1 Answers1

0

It will search for the exact string print({}). It seems like you need the text within that print statement, its better to use regex and find text between print( and ). See https://stackoverflow.com/a/3369000/7334699

I don't know what your goal exactly is, but you can also take a look at the eval() function which just runs python code within a string.

ToTheMax
  • 981
  • 8
  • 18