我有一个包含python代码的文本文件。我需要读取文本并使用compile()检查错误。我不能直接编译文件,因为我需要在编译前删除一些文本。当我从文件中读取字符串时,它总是显示由于\n字符而导致的语法错误。我该如何解决这个问题?
------file.txt---------------
print('hello')
print('world')
-----------------------------
------test.py----------------
f = open("/filepath/file.txt", "r")
codecontent = f.read()
f.close()
compile(codecontent, '', 'eval')
###output####
Syntaxerror at line 1 -> "print('hello')\n"
试试这段代码。
with open('filepath/file.txt') as f:
for line in f:
x = compile(line, 'test', 'eval')
exec(x)
if 'str' in line:
break