Dani DcTurner
Dani DcTurner

Reputation: 83

How to write console output on text file

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

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"

Upvotes: 8

Views: 48943

Answers (1)

maguri
maguri

Reputation: 454

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

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

Upvotes: 21

Related Questions