Black Lives Matter - Action and Equality. ... Adafruit is open and shipping.
0

Writing to a txt file
Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.

Writing to a txt file

by PioLew on Fri Jun 12, 2020 3:08 pm

Hello,
I am absolutely new to CircuitPython, though quite experienced in Python. I work on Feather M4 Express. To make the long story short, the code below creates a "test.txt" file, as expected (please see attached), but writes the whole input into one line. It looks like it does not recognize the "\n" for jumping to a new line, which is a normal behavior in Python. What am I doing wrong? The boot.py checks the D5-Gnd for allowing CP to write, which - in principle - seems to work as expected.

The code (main.py) is:

import board
import analogio
import time

input_pin = analogio.AnalogIn(board.A1)

def voltage(pin): ## reads-in voltage regulated by a potentiometer connected to A1
return (pin.value * 3.3) / 2 ** 16

with open("test.txt", "a") as inf:
for i in range(10):
vlt = round(voltage(input_pin), 3)
inf.write("{}\n".format(vlt)) ## I expect one line in "test.txt" per one reading every 0.5 sec.
time.sleep(0.5)


BTW: just checked with writing-in simply "Hello World"; the same stuff: 10 times in one line!
Thanks a lot in advance for comments and support.
Greetings,
Piotr
Attachments
test.txt
(60 Bytes) Downloaded 3 times

PioLew
 
Posts: 2
Joined: Fri Jun 12, 2020 2:44 pm

Re: Writing to a txt file

by dastels on Fri Jun 12, 2020 3:18 pm

What OS are you using? I believe Windows still requires /r/n as a line terminator.

FYI, the attached file is fine in Linux: one number per line, 10 lines total.

Dave

dastels
 
Posts: 2829
Joined: Tue Oct 20, 2015 3:22 pm

Re: Writing to a txt file

by PioLew on Fri Jun 12, 2020 3:55 pm

Dave, thanks a lot!
Indeed I use Windows, and \r\n fixes the issue (backslashed).
Have a nice evening,
Piotr

PioLew
 
Posts: 2
Joined: Fri Jun 12, 2020 2:44 pm

Re: Writing to a txt file

by dastels on Fri Jun 12, 2020 4:00 pm

Excellent! Enjoy the weekend.

Dave

dastels
 
Posts: 2829
Joined: Tue Oct 20, 2015 3:22 pm

Please be positive and constructive with your questions and comments.