2

i have a small program for receiving a txt file from an arduino. the problem is sometimes it prints an empty file. i assume because the receiving part of the code is empty at the time. can someone help me make this code not write to the file when "t" is empty so i can prevent it from writing a blank txt file? thanks

with open('sensData.txt','wb') as f:
while True:
 t = conn.recv(20)
 print t
 if not t:
    s.close()
    break
 f.write(t) #Write To File UNLESS BLANK
2
  • 1
    How would you distinguish between end-of-file and simply a transfer “hiccup” then? You’d probably have to introduce a simple timeout to do that. Commented Mar 28, 2018 at 9:28
  • thats a good point. i dont know what to do at this point. ive only been learing python for 4 days now. what could i do to prevent a write on a corrupted transfer or a blank txt file, which is probably what is happening in the first place Commented Mar 28, 2018 at 9:33

2 Answers 2

1

you need to try this :

  with open('sensData.txt','wb') as f:
    while True:
     t = conn.recv(1)
     print t
     if t =='':
        s.close()
        break
     f.write(t)

or you can populate a string and write it at once at the end of the loop

  with open('sensData.txt','wb') as f:
   receivedData = ""
    while True:
     t = conn.recv(1)
     print t
     if t =='':
        s.close()
        break
     receivedData+=t

   f.write(receivedData)
Sign up to request clarification or add additional context in comments.

6 Comments

thankyou soo much, this answer my first question. another big problem i have is, i run this program in a batch script loop on windows for the time being which works except sometimes it freezes at calling the script. which probably is a messed up connection/transfer. what can i implement to prevent the scipt freezing at a corrupted connection?
I think with these changes you will not face this issue can you please try and share your experience?
yes thankyou im using it now. sometimes i wont have a problem for hours. now time will tell
accept the answer if you think the problem is solved
its still writing a blank file, altho t does = the received data? the problem is i cant let it print anything to the file if its blank ever
|
0
if t != "":
    f.write(t)

if t is empty, this should work

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.