Python Forum

Full Version: How to store continous output into a text file?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am new to the Python coding , so anyone please guide me. I want to store the output into a text file. From the below code, i am able to read the data in a Python Shell.

[python]
import serial.tools.list_ports

list = serial.tools.list_ports.grep('VID:PID=10C4:EA60','hwid')
connected = []
for element in list:
connected.append(element.device)
a=str(connected)

try:
port = connected[0]
baud = 115200
ser = serial.Serial(port, baud, timeout=1)
#input1.encode('UTF-8')
if ser.isOpen():
print(ser.name + ' is open...')
while (1):
out1 = ser.read()
print out1,
ser.close()
except:
pass
For above code, i got the below output
Output:
tx data=10513 tx data=10514 tx data=10515 tx data=10516 tx data=10517 tx data=10518 tx data=10519 4 tx data=10520 tx data=10521 tx data=10522

  1. Use BBCode
  2. Use Python 3.x or from __future__ import print_function
  3. Open a file in append mode.
  4. Use a context manager:
    with open('file', 'a') as fd:
        # code
        pass
    # leaving the block, guarantees that the file is closed
  5. Use fd.write('your data')
  6. Alternative you can use the print function. The function takes different arguments/keywords. The file keyword is the fileobject, where the print function writes it output. Additionally a newline is added automatic. You can also control sep (seperator) and end (newline).
    # inside the with block
    print('your data', file=fd)