Skip to main content
 首页 » 编程设计

Python读取文本 block

2024年10月24日11小虾米

我在尝试正确读取文件时遇到了一些问题。

我只有一个代码来显示我的目标。但是我想读取每个数据 block (四行)并将每个数据 block 插入一个数组中。我还需要将“城市”、“州”和“ zip ”彼此分开。

我知道我应该读取文件,对于我读取的每个 block ,直到一个空行,在其中我会检查它是否是第三行,如果是,则将每个部分解析为它自己的元素,并且做这一切直到最后。但是,我在 Python 的编码部分遇到了麻烦。我对 Python 不太熟悉。

我的数据:

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

我的代码:

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()  

这会在 mylist 中创建所有空元素。

请您参考如下方法:

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