从文本文件中编译python代码,在python程序中显示出语法错误,原因是有一个/n字符。

问题描述 投票:0回答:1

我有一个包含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"
python compilation file-read
1个回答
0
投票

试试这段代码。

with open('filepath/file.txt') as f:
for line in f:
   x = compile(line, 'test', 'eval')
   exec(x)
   if 'str' in line:
      break
© www.soinside.com 2019 - 2024. All rights reserved.