我有一个文件,其中包含美国的所有邮政编码以及它们的纬度和经度。该文件的格式为ZIP,LAT, LONG\n
。
我打算将它们保存到数据库中,因此我逐字遍历了文件并设置了counter
变量。如果counter == 1
应该将值分配给zip_codes[]
,如果counter == 2
将值分配给latitude[]
并且如果counter == 3
将值分配给longitude[]
,但是,当我运行以下代码来测试它是否正确添加了邮政编码值时,它变成了一个无限循环,我不得不强制退出IDLE
(可以在here上查看文件)
zip_code_file = open('zip_codes.txt')
zip_codes=[]
latitude=[]
longitude = []
counter = 1
for s in zip_code_file.read().split(','):
s = s.strip()
if counter ==1:
zip_codes.append(s)
counter = counter +1
elif counter == 2:
latitude.append(s)
counter = counter+1
elif counter == 3:
longitude.append(s)
counter = 1
print(zip_codes)
有人知道这是怎么回事吗?
答案 0 :(得分:2)
您需要少一点循环:
zip_code_file = open('zip_codes.txt')
zip_codes = []
latitude = []
longitude = []
for line in zip_code_file:
zipcode, lat, lng = line.strip().split(',')
zip_codes.append(zipcode)
latitude.append(lat)
longitude.append(lng)
print(zip_codes)
答案 1 :(得分:1)
逗号分隔值的文件应使用csv
模块
import csv
with open('zip_codes.txt') as f:
r = csv.reader(f)
next(r) # skip the header
zip_codes, latitudes, longitudes = zip(*r)