简体   繁体   English

Python脚本没有写入txt文件

[英]Python script not writing to txt file

I have a Python script that runs properly on my laptop, but when running on my raspberry pi, the following code does not seem to be working properly. 我有一个在我的笔记本电脑上正常运行的Python脚本,但是当我在我的覆盆子pi上运行时,以下代码似乎无法正常工作。 Specifically, "TextFile.txt" is not being updated and/or saved. 具体而言,“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()

I am seeing "test 1" and "test 2" in my output, so I know that the code is being reached, paths are correct, etc 我在输出中看到“测试1”和“测试2”,所以我知道代码正在到达,路径是正确的,等等

It may be due to a permissions problem. 这可能是由于权限问题。 I am running the script from the terminal by using: 我使用以下命令从终端运行脚本:

   usr/bin/python PATH/script.py

Python is owned by "root" and script.py is owned by "Michael". Python由“root”拥有,script.py由“Michael”拥有。

Since your code is running, there should be a file somewhere. 由于您的代码正在运行,因此应该有一个文件。

You call "PATH/script.py", but there is "/PATH/TextFile.txt" in your program. 你调用“PATH / script.py”,但程序中有“/PATH/TextFile.txt”。 Is the slash before PATH a mistake? PATH之前的斜线是错误吗? Have you checked the path in your program is really where you are looking for the output file? 您是否检查过程序中的路径是否正在寻找输出文件?

My first guess: 我的第一个猜测:

Does the file exist? 该文件是否存在? If it does not exist then you cannot write to it. 如果它不存在那么你就不能写它。 Try this to create the file if it does not exist: file = open('myfile.dat', 'w+') 如果文件不存在,请尝试此操作: file = open('myfile.dat', 'w+')

Additionally manually opening and closing file handles is bad practice in python. 另外,在python中手动打开和关闭文件句柄是不好的做法。 The with statement handles the opening and closing of the resource automatically for you: with语句自动为您处理资源的打开和关闭:

with open("myfile.dat", "w+") as f:
    #doyourcalculations with the file object here
    for line in f:
        print line

All, thank you for your input. 全部,谢谢你的意见。 I was able to figure out that it was writing to the new file, but it was overwriting with the same text. 我能够发现它正在写入新文件,但它被覆盖了相同的文本。 The reason was because ".startswith" was returning false when I expected true. 原因是因为“.startswith”在我预期为真时返回了假。 The misconception was due to the difference between how Windows and Unix treat new line characters (/n /r). 误解是由于Windows和Unix如何处理新行字符(/ n / r)之间的差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM