我是编程新手,我在网页上搜索了这个问题的答案,并尝试了许多可能性但没有成功。我目前设法将电位计连接到我的树莓派并在控制台上获取值,但我不知道如何将这些值保存到文本文件中。这是我的代码:
#!/usr/bin/python
import spidev
import time
#Define Variables
delay = 0.5
ldr_channel = 0
#Create SPI
spi = spidev.SpiDev()
spi.open(0, 0)
def readadc(adcnum):
# read SPI data from the MCP3008, 8 channels in total
if adcnum > 7 or adcnum < 0:
return -1
r = spi.xfer2([1, 8 + adcnum << 4, 0])
data = ((r[1] & 3) << 8) + r[2]
return data
while True:
ldr_value = readadc(ldr_channel)
print ('---------------------------------------')
print("LDR Value: %d" % ldr_value)
time.sleep(delay)
file = open('data.txt','w')
file.write("LDR Value: %d" % ldr_value)
file.close()`
从代码中可以看出,我可以将最后一个值获取到 data.txt 中,但不能及时获取所有值。非常感谢您,我很抱歉我的“菜鸟”
最佳答案
当您在终端中执行文件时,您可以将此脚本的输出重定向到这样的文件:
$ python script.py > /the/path/to/your/file
在 Python 中你只需要设置
sys.stdout
到一个文件,然后,所有的打印将被重定向到 /the/path/to/your/file
.import sys
sys.stdout = open('/the/path/to/your/file', 'w')
并且不要忘记在脚本末尾关闭文件;)
sys.stdout.close()
关于python-3.x - 如何在文本文件上编写控制台输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47699023/