Python脚本不写入txt文件

标签 python linux permissions

我有一个 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/

相关文章:

python - 将列表的每个元素写在 Python 文本文件的换行符上

python - matplotlib如何将每个子图x标签,y标签设置在一起

linux - 粘贴公钥的位置

c++ - 用于 win32、linux、mac 的 POSIX C 包装器

php - 强制 PHP CLI 将文件写入 www-data

python - 如何在 Pycharm 的 Google 风格 Pydoc 中表示返回类型元组?

python - 定义正确的requirements.txt文件

linux - 如何检查父目录 bash 中是否存在给定的目录名称

linux - 如何在 Linux 中以 root 权限运行脚本

google-cloud-platform - 访问/管理 map 自动完成等 API 服务需要哪些 GCP IAM 权限?