Python: Select particular characters from a file and add them to a new variable
<p>I'm fairly new to python and I'm not sure why what I'm doing is wrong.</p>

<pre><code>numberOfOrders = 0
numberOfProducts = 0

allOrders = open("file.txt", "r") #A .txt file in the same directory as the .py file.
#file.txt: 
#(A-&gt;[a:20,a:20,b:10,c:25,c:25])
#(B-&gt;[d:100,e:70])
#(C-&gt;[f:10000,g:200000])

while True:
        theline = allOrders.readline()
        for theline in allOrders:
            for char in theline: #Iterate over each character of a line.
                listProducts = "" #Empty string, will be the concatenation of the wanted characters.
                if char == "[": #Wanted character.
                    listProducts = listProducts + "["
                elif char == ":": #To keep count of no. of products in a list.
                    numberOfProducts += 1
                elif is_number(char) == True: #Function that checks whether char is a number.
                    listProducts = listProducts + str(char) #Add to the string "listProducts".
                elif char == ",": #Wanted character.
                    listProducts = listProducts + str(char)
                elif char == "]":#Wanted character, to end the string.
                    listProducts = listProducts +str(char)
                    break
            numberOfOrders += 1 #To keep track of no. of orders. Each line of file is an order. 
        if len(theline) == 0:
            break

    allOrders.close()

    print(numberOfProducts)
    print(numberOfOrders)
    print(listProducts)
</code></pre>

<p>I basically only want the numbers and commas within brackets. That's my biggest issue here.
The output I get for</p>

<pre><code> print(listProducts)
</code></pre>

<p>is</p>

<pre><code> ]
</code></pre>

<p>Thank you.</p>

<p>Regarding your code, the solution is to:</p>

<ol>
<li>Removing the "for theline in allOrders" which is not coherent</li>
<li>Moving the initialization of listProducts before the while loop  </li>
</ol>

<p>Of course this can be widely optimized using regex for example, as suggested by tdelaney.</p>

python file python-3.x if-statement for-loop