-2

I have a code which is using with statement to read a file line by line. The below code goes in infinite loop where line:1 is printed everytime. Not sure what mistake I am doing

  with open (config_file) as fp:
        line = fp.readline()
        print("line is", line)
        while line:
            match = re.search("^QueueDir\s*=\s*(.*)$", line)
            if (match.group(1)):
                return match.group(1)
Sumit
  • 1,953
  • 6
  • 32
  • 58

2 Answers2

1

Your variable fp is a file handle, use for loop for easy access of elements in the loop.

with open (config_file) as fp:
    for line in fp:
        match = re.search("^QueueDir\s*=\s*(.*)$", line)
        if (match.group(1)):
            return match.group(1)

The code goes to infinite loop because of the while condition, while line:, in the case of conditions, any non-zero values are considered as True, so as line is non-empty, the condition is interpreted as while True, so it runs infinitely.

tripleee
  • 175,061
  • 34
  • 275
  • 318
Roshin Raphel
  • 2,612
  • 4
  • 22
  • 40
  • 1
    `lines = fp.readline()` only reads one line. Your `for` loop ends up iterating over its individual characters. You want `for line in fp:` instead, plain and simple. Also, the `print` refers to an uninitialized variable. – tripleee Jul 23 '20 at 11:52
  • @tripleee `print("line is", line)` came from OP's code, I didn't notice it, my mistake. – Roshin Raphel Jul 23 '20 at 11:57
  • 1
    "Your variable is a list" is still not true, but I guess you can fix that too. – tripleee Jul 23 '20 at 12:08
0

add line = fp.readline() at the end of your while loop. As line does not changes from one loop to the next.

  with open (config_file) as fp:
        line = fp.readline()
        print("line is", line)
        while line:
            match = re.search("^QueueDir\s*=\s*(.*)$", line)
            if (match.group(1)):
                return match.group(1)
            line = fp.readline()
solmans
  • 517
  • 6
  • 14
Maug
  • 35
  • 8