Python 3 个问题编辑测试文件

Python 3 issues editing test files

在 raspbian 中,我试图用 Python 3 编写一个程序,将所有运动记录在一个文本文件中。

PS: 我正在使用连接到 GPIO 26 的 PIR 传感器, 文本文件名为 Test.txt

  import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(26, GPIO.IN)
f = open('Test.txt', 'a+')

while True:
    if GPIO.input(26):
        import datetime
        f.write (time.strftime("\n\n%a %b %d %I:%M:%S %p"))
        f.close()
        time.sleep(5)
    else:
        time.sleep

我的程序工作正常,直到第二次触发传感器。在 LXTerminal 中出现此错误。

pi@raspberrypi ~/Desktop $ sudo python MotionSensorLogtest.py

Traceback (most recent call last):

  File "MotionSensorLogtest.py", line 10, in <module>

    f.write (time.strftime("\n\n%a %b %d %I:%M:%S %p"))

ValueError: I/O operation on closed file

pi@raspberrypi ~/Desktop $ 

I have been working on this project for quite a while. But, whenever I try to use another post's solution, it either doesn't work, or I can't figure out how to implement it into my program. Please try to understand that I'm just beginning to program, and will probably need one of those "I have no idea what I am doing" explanations.

谢谢,如有任何帮助,我们将不胜感激。

您将在写入文件 (f.close()) 后将其关闭。您可能想要 flush() 该文件,以便立即写入所有数据,并且不会将任何内容存储在缓冲区中(这意味着,如果此脚本突然中断或 Python 被杀死,则不会丢失任何数据).

顺便说一下,我认为您没有正确使用 time.sleep。在 else 的情况下,你应该 调用 它(使用 time.sleep() -> 使用括号),而不仅仅是 'mention' 就像您在当前代码中所做的那样。

您在程序开始时打开文件一次,但每次尝试写入时都将其关闭。只需将对 f.close 的调用移动到 while 循环之后。如果您发现您的数据没有像您预期的那样频繁地进入文件,您可能需要添加一个 flush 调用。例如:

f = open(...)

while True:
    if GPIO.input(26):
        import datetime
        f.write (time.strftime("\n\n%a %b %d %I:%M:%S %p"))
        f.flush()
        time.sleep(5)
    else:
        time.sleep

f.close()