Storing string from arduino to text file using python

I am using this code to send a string from arduino to PC

int i=0;
void setup(){
Serial.begin(9600); // Open serial connection at a baud rate of 9600
pinMode(13, OUTPUT); //set pin13 in o/p mode

void loop(){

I need a python code that receives this string and store it in a text file as such.The arduino is transmitting this string continuously but i need it only once in the text file. I have written the below code but am getting only unexpected values in the text file

import the serial library

import serial

Boolean variable that will represent

whether or not the arduino is connected

connected = False

establish connection to the serial port that your arduino

is connected to.


for device in locations:
print “Trying…”,device
ser = serial.Serial(device, 9600)
print “Failed to connect on”,device

loop until the arduino tells us it is ready

while not connected:
serin =
connected = True

open text file to store the current

##gps co-ordinates received from the rover
text_file = open(“position4.txt”, ‘w’)

read serial data from arduino and

write it to the text file ‘position.txt’

if x=="\0":

close the serial connection and text file


How do you know the values are "unexpected"?

Did you read the posting guidelines?
Why not?

I cannot comment on the Python code but if it is as bad as your Arduino code then all bets are off. Why do you have thewhile(1)in your code when the loop() function does that for you anyway ?

I assume that there is a reason why you are sending the same string multiple times when you only need it once on the PC but you have not said. If it is only needed once then maybe you should only send it once.