python-3.x - 如何在文本文件上编写控制台输出

标签 python-3.x file text console output

我是编程新手,我在网页上搜索了这个问题的答案,并尝试了许多可能性但没有成功。我目前设法将电位计连接到我的树莓派并在控制台上获取值,但我不知道如何将这些值保存到文本文件中。这是我的代码:

 #!/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/

相关文章:

python - 尝试将字符串中特定位置的字符设置为另一个字符

python - 如何使用 praw 从 reddit 下载视频

python - 如何使用带有输入函数的for循环

sql-server - 使用 Powershell 从存储过程返回的数据(大型 XML 文件)从 ReportServer 输出 XML 时如何停止截断数据

python-3.x - 将参数传递给定义的函数,以便它们可以在 python3 中访问 sys.argv

c++ - Getline 函数不解析 CSV 文件中的行尾

java - 如何在Java中有效地到达文本文件的末尾?

python - 去除低频词

java - 如何在Android Studios中使用fileReader读取文本文件数据?

text - 如何在 ModalRoute 上设置状态()?