Gitzee Gitzee - 1 year ago 80
Python Question

Python: Select particular characters from a file and add them to a new variable

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.

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)
numberOfOrders += 1 #To keep track of no. of orders. Each line of file is an order.
if len(theline) == 0:



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




Thank you.

Answer Source

Regarding your code, the solution is to:

  1. Removing the for theline in allOrders which is not coherent
  2. Moving the initialization of listProducts before the while loop

Of course this can be widely optimized using regex for example, as suggested by @tdelaney.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download