文件路径:
"C: deana OneDrive 用户马龙的Python编程文件 皮特 PITT_LIbrary 列表 test.txt"
代码行如下:
import os
os.chdir("C:/Users/deana/OneDrive/Marlon's files/Programming/Python/PITT/PITT_LIbrary/Lists")
exec(open('test.txt'))
错误如下:
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
exec(open('test.txt'))
TypeError: exec() arg 1 must be a string, bytes or code object
同样,如果我在一行中尝试这样做:
exec(open(r"C:/Users/deana/OneDrive/Marlon's files/Programming/Python/PITT/PITT_LIbrary/Lists/test.txt"))
也是同样的错误。(带或不带r)
超级沮丧,因为它读起来像我没有输入字符串…但是是字符串!?!我以前也用同样的方法做过这个,重新启动IDLE shell,没有区别。啊!我总是在文件路径上遇到愚蠢的错误。
我应该使用os.startfile()
来打开这个。使用.open()会让人感到困惑。当我试图打开默认应用程序时。以前,我已经使用exec.open()打开.py文件,我猜我把它们弄混了。Exec只是用来打开其他脚本…下次需要更浓的咖啡。
试试这个:
import os
os.chdir("C:/Users/deana/OneDrive/Marlon's files/Programming/Python/PITT/PITT_LIbrary/Lists")
exec(open('test.txt', 'rb'))
您可以通过使用rb
(r打开txt文件将其转换为字节b o欧美)。