我在尝试正确读取文件时遇到了一些问题。
我只有一个代码来展示我想要达到的目标。但我想读取每个数据 block (四行)并将每个数据 block 插入到一个数组中。我还需要将“城市”、“州”和“邮政编码”彼此分开。
我知道我应该读取该文件,对于我读取的每个 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
关于Python 读取文本 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33535090/