如何在文本文件上编写控制台输出 [英] How to write console output on text file

查看:73
本文介绍了如何在文本文件上编写控制台输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to programming and I've searched the webpage for the answer to this question and have tried many possibilities without success. I have currently managed to connect a potentiometer to my raspberry and get values on the console, but I don't know how to save these values onto a text file. This is my code:

 #!/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 中,但不能及时获取所有值.非常感谢您,我很抱歉我的noobness"

As you can see from the code, I can get the last value onto data.txt, but not all the values in time. Thank you very much in advance and I am sorry for my "noobness"

推荐答案

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

When you execute a file in the terminal, you can redirect the outputs of this script to a file like this:

$ python script.py > /the/path/to/your/file

在 Python 中,您只需将 sys.stdout 设置为一个文件,然后所有打印将被重定向到 /the/path/to/your/file.

In Python you just have to set the sys.stdout to a file and then, all the prints will be redirected to /the/path/to/your/file.

import sys
sys.stdout = open('/the/path/to/your/file', 'w')

并且不要忘记在脚本末尾关闭文件;)

and do not forget to close the file at the end of your script ;)

sys.stdout.close()

这篇关于如何在文本文件上编写控制台输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆