我有一个 Python 脚本可以在我的笔记本电脑上正常运行,但是在我的树莓派上运行时,以下代码似乎无法正常运行。具体来说,“TextFile.txt”没有被更新和/或保存。
openfile = open('/PATH/TextFile.txt','w')
for line in lines:
if line.startswith(start):
openfile.write(keep+'\n')
print ("test 1")
else:
openfile.write(line)
print ("test 2")
openfile.close()
我在输出中看到“测试 1”和“测试 2”,所以我知道正在访问代码、路径正确等
这可能是由于权限问题。我正在使用以下命令从终端运行脚本:
usr/bin/python PATH/script.py
Python 归“root”所有,script.py 归“Michael”所有。
最佳答案
我的第一个猜测:
文件是否存在?如果它不存在,那么你不能写入它。如果文件不存在,请尝试创建该文件:file = open('myfile.dat', 'w+')
此外,手动打开和关闭文件句柄在 Python 中是不好的做法。 with 语句自动为您处理资源的打开和关闭:
with open("myfile.dat", "w+") as f:
#doyourcalculations with the file object here
for line in f:
print line
关于Python脚本不写入txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36825609/