How to write console output on text file

17,039

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()
Share:
17,039
Dani DcTurner
Author by

Dani DcTurner

Updated on June 04, 2022

Comments

  • Dani DcTurner
    Dani DcTurner almost 2 years

    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"

  • Dani DcTurner
    Dani DcTurner over 6 years
    How do i do that??
  • dmitriy
    dmitriy over 4 years
    @maguri What I need to do if I want that all the script will be printed to specific file. Even all the assign of a variable, like a=2, will be printed to the file?