1

I'm reading in a list of samples from a text file and in that list every now and then there is a "channel n" checkpoint. The file is terminated with the text eof. The code that works until it hits the eof which it obviously cant cast as a float

log = open("mq_test.txt", 'r')
data = []
for count, sample in enumerate(log):
    if "channel" not in sample:
        data.append(float(sample))
        
print(count)
log.close()

So to get rid of the ValueError: could not convert string to float: 'eof\n' I added an or to my if as so,

log = open("mq_test.txt", 'r')
data = []
for count, sample in enumerate(log):
    if "channel" not in sample or "eof" not in sample:
        data.append(float(sample))
        
print(count)
log.close()

And now I get ValueError: could not convert string to float: 'channel 00\n'

So my solution has been to nest the ifs & that works.

Could somebody explain to me why the or condition failed though?

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
DrBwts
  • 3,470
  • 6
  • 38
  • 62
  • 4
    It did not fail. `"eof"` was not in sample, therefore the `or` condition _as a whole_ was true. You might want `and` instead of `or`. – John Gordon Feb 15 '23 at 16:18

2 Answers2

1

I think you need to use and operator not or since both "channel" and "eof" are strings and they cannot be typecasted into float, also try to do grouping so:

log = open("mq_test.txt", 'r')
data = []
for count, sample in enumerate(log):
    if ("channel" not in sample) and ("eof" not in sample):
        data.append(float(sample))
        
print(count)
log.close()
Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
0

I think it's a logic issue which "and" might be used instead of "or"

Joey
  • 111
  • 8