Search code examples
pythonparsingscanning

Python reading chunks of text


I am running into some problems trying to read a file correctly.

I only have a code to show what I'm trying to aim for slightly. But I want to read each chunk of data (four lines) and insert each of those chunks into an array. I also need to separate 'city', 'state', and 'zip' from each other.

I understand that I'm supposed to read the file, for each chunk I read until an empty line, within that I would check to see if it is the third line and if so parse each part into its own element, and do all that till the end. I am, however, having trouble with the coding part with Python. I am not too familiar with Python.

My data:

Name
address
city, state zip
phone number
//empty line
Name
address
....

My code:

with open('tester_everything.txt') as f:                                                                                                                  
mylist = []                                                                                                                                             
i=0                                                                                                                                                     
for lines in f:                                                                                                                                         
  other_list = []        
  if lines == '\n':
    mylist.append(other_list)
    other_list = []

  other_list.insert(i, lines)                                                                                                                    
  i = i+1                                                                                                                                               
print mylist                                                                                                                                            
f.close() 

This creates all empty elements inside mylist.


Solution

  • with open('tester_everything.txt') as f:                                                                                                                  
        mylist = []  
        other_list = []                                                                                                                                                   
        for lines in f:                                                                                                                                         
            if lines == '\n':
                mylist.append(other_list)
                other_list = []
            else:
                other_list.append(lines)                                                                                                                                                                                                                                                                 
        print mylist