【问题标题】:How to write console output on text file如何在文本文件上写入控制台输出
【发布时间】:2018-05-21 19:03:45
【问题描述】:

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

 #!/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-3.x file text console output


    【解决方案1】:

    当您在终端中执行文件时,您可以将此脚本的输出重定向到如下文件:

    $ 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()
    

    【讨论】:

    • 我该怎么做??
    • @maguri 如果我希望将所有脚本打印到特定文件,我需要做什么。甚至变量的所有赋值,比如 a=2,都会打印到文件中?
    猜你喜欢
    • 1970-01-01
    • 2012-02-01
    • 2011-03-17
    • 1970-01-01
    • 2012-12-18
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多