2016-02-28 101 views
0

当我运行此:蟒蛇的ReadLine文件

import os.path 
import pyproj 
srcProj = pyproj.Proj(proj='longlat', ellps='GRS80', datum='NAD83') 
dstProj = pyproj.Proj(proj='longlat', ellps='WGS84', datum='WGS84') 
f = file(os.path.join("DISTAL-data", "countries.txt"), "r") 
heading = f.readline() # Ignore field names. 
with open('C:\Python27\DISTAL-data\geonames_20160222\countries.txt', 'r') as f:   
    for line in f.readlines(): 
    parts = line.rstrip().split("|") 
    featureName = parts[1] 
    featureClass = parts[2] 
    lat = float(parts[9]) 
    long = float(parts[10]) 
    if featureClass == "Populated Place": 
     long,lat = pyproj.transform(srcProj, dstProj, long, lat) 
    f.close() 

我得到这个错误:

File "C:\Python27\importing world datacountriesfromNAD83 toWGS84.py", line 13, in for line in f.readlines() : MemoryError.

我已经下载了国家从http://geonames.nga.mil/gns/html/namefiles.html文件作为整个国家文件数据集。

请帮我解决这个问题。

回答

2

readlines方法()对于大文件在内存中创建一个大的结构,你可以尝试使用:由耶尔给出

f = open('somefilename','r') 
for line in f: 
    dosomthing() 
2

答案是有帮助的,我想改善它。一个很好的方式来读取一个文件或大文件

with open(filename) as f: 
    for line in f: 
     print f 

我喜欢用“有”,这确保文件将被正确关闭的语句。