Extracting a specific value from txt file using python
Extracting a specific value from txt file using python
I have a set of data I'm working with that appears in a text file like:
Sensor Data
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?
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).– dashiell
Jun 29 at 18:11
line.split()
line.split('t')
@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.
– user10012049
Jun 29 at 18:11
got it. There is an empty list in between.
– Mufeed
Jun 29 at 18:16
you have a blank line i guess
– Mufeed
Jun 29 at 18:17
3 Answers
3
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)
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])
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.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
if you want to split by white space just use line.split() .No need to add " "
– Mufeed
Jun 29 at 18:05