I'm fairly new to python and I'm not sure why what I'm doing is wrong.
numberOfOrders = 0
numberOfProducts = 0
allOrders = open("file.txt", "r") #A .txt file in the same directory as the .py file.
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)
numberOfOrders += 1 #To keep track of no. of orders. Each line of file is an order.
if len(theline) == 0:
Regarding your code, the solution is to:
for theline in allOrderswhich is not coherent
listProductsbefore the while loop
Of course this can be widely optimized using regex for example, as suggested by @tdelaney.