0

I have a set of data I'm working with that appears in a text file like: Sensor Data

enter image description here

I want to extract the RSSI data from each line of code.

with open ('datasensorsmall.txt') as f:
for line in f:
    TS, Drop, RX, TX, RSSI, CRCData, light, temp, humidity = line.split("   ")
    print(RSSI)

However, it only prints the first RSSI value and then I get an error value that says:

"ValueError: not enough values to unpack (expected 9, got 1)". 

How do I solve` this?

12
  • 2
    if you want to split by white space just use line.split() .No need to add " " Commented Jun 29, 2018 at 18:05
  • I imagine that the data is tab separated and not space separated, which is why that's not working. line.split() or line.split('\t') (if you don't want to split on all whitespace). Commented Jun 29, 2018 at 18:11
  • @Mufeed I get an error that says "ValueError: not enough values to unpack (expected 9, got 0)". It prints out the first line's RSSI value, which leads me to think there's something going wrong in the iteration of the code. Commented Jun 29, 2018 at 18:11
  • 1
    got it. There is an empty list in between. Commented Jun 29, 2018 at 18:16
  • 1
    you have a blank line i guess Commented Jun 29, 2018 at 18:17

3 Answers 3

1

The problem is there is a blank line in the text file. So to avoid such scenarios, you could use something like

with open ('datasensorsmall.txt') as f:
    for line in f:
        if not line.strip():   # this line will ignore blank line
            TS, Drop, RX, TX, RSSI, CRCData, light, temp, humidity = line.split()
             print(RSSI)
Sign up to request clarification or add additional context in comments.

Comments

0

You can use Regex for this

import re
with open ('datasensorsmall.txt') as f:
for line in f:
    rssi = re.findall('RSSI:(.*?)\s*C', line)
    print(rssi[0])

2 Comments

Thanks, I used this and it worked for my RSSI values, but I also want to collect my light values. What does .*?)\s*C mean in the code?
If it helped you kindly upvote it. Back to your question, RSSI:(.*?)\s*C it is a regex pattern which means after 'RSSI:' whatever(.*?) there is just capture that until one or more space(\s*) followed by character 'C'
0

Not enough values to unpack means your split is not yielding enough strings to assign to all of those variables.

So throw in a conditional if length of split is 9, then do your assignment.

Or avoid multiple assignment because this isn’t well suited to it, and just iterate through your split, assigning to as many target variables as strings your split yields.

Comments

Your Answer

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