0

This is probably too basic but let me ask anyway!

I'm looking for a way to get a field number that contains my match so that I can do more work based on the result.

I tried something like:

with open(filename) as f:
  for line in f:
    for field in range(-1, 0,-1):  # Wrong --> How can I decrement starting from the last field backwards to the 1st field in each line of a file?
      if pattern in field:
        print("field# " + field + " shows:" + line.split(' ')[field])

Thanks in advance!

- Steve

Steve
  • 337
  • 1
  • 4
  • 13
  • 1
    When you ask "how else should I do this?" it is unclear exactly what result you are imagining. Can you elaborate on how "fields" are represented in your file and show the expected output from an example input? If forced to guess (and currently we *are* forced to guess) I'd say you might want to `.split()` each line and then iterate over the output of `enumerate()` applied to the resulting list. – jez Nov 04 '19 at 19:37
  • I agree with @jez. What's the intention of `range(1, 0,-1)`? What is `pattern`? – wjandrea Nov 04 '19 at 19:39
  • Sorry for the typo, it's range(-1, 0, -1) to decrement from the last field (-1) to the first field (0). – Steve Nov 04 '19 at 19:41
  • 1
    Does this answer your question? [Traverse a list in reverse order in Python](https://stackoverflow.com/questions/529424/traverse-a-list-in-reverse-order-in-python) – jez Nov 04 '19 at 19:42
  • provide a good example(s) of input and output. – Serge Nov 04 '19 at 19:47

1 Answers1

0

Assume you do not care on which line it happens, and fields are counted from 1 and not -1.

with open(filename) as f:
  for line in f:
    fields = line.split() # assume white space is delimiter
    for i, field in enumerate(fields, 1): 
      if pattern in field:
        print("field# " + i + " shows:" + field)
Serge
  • 3,387
  • 3
  • 16
  • 34
  • It turns out the OP specifically wants to go through fields in reverse order. If you were to use `reversed(list(enumerate(...)))` then your answer would solve it. – jez Nov 04 '19 at 19:46
  • Looks like. Why he cannot explain it to everybody so it answer matches the question? Is there a reason for doing reversal? – Serge Nov 04 '19 at 19:49