2016-10-24 37 views
1

我试图转换具有以下列的CSV文件:csv文件转换为另一种CSV选择特定的列蟒蛇

 
ID,Name,Postcode,State,Suburb,Lat,Lon 
1,Hurstville Store,1493,NSW,Hurstville,-33.975869,151.088939 

我想和新的CSV只有名称,纬度,经度列,但即时得到这个错误: 头= csvReader.next() AttributeError的: '_csv.reader' 对象有没有属性 '下一个'

这里是我到目前为止的代码:

import csv 

# Set up input and output variables for the script 
storeLoc = open("store_locations.csv", "r") 

# Set up CSV reader and process the header 
csvReader = csv.reader(storeLoc) 
header = csvReader.next() 
nameIndex = header.index("Name") 
latIndex = header.index("Lat") 
lonIndex = header.index("Lon") 

# Make an empty list 
coordList = [] 

# Loop through the lines in the file and get each coordinate 
for row in csvReader: 
name = row[nameIndex] 
lat = row[latIndex] 
lon = row[lonIndex] 
coordList.append([name,lat,lon]) 

# Print the coordinate list 
print(coordList) 
coordList.append([name,lat,lon]) 

stores = open('store_coords.csv','w', newline='') 

感谢您的任何反馈

回答

0

该代码将在Python 2中工作,即csv.reader对象有一个next()方法。但是,在Python 3中没有这样的方法。

相反,这一点也适用在Python的两个版本,使用next(reader)

import csv 

# Set up input and output variables for the script 
storeLoc = open("store_locations.csv", "r") 

# Set up CSV reader and process the header 
csvReader = csv.reader(storeLoc) 
header = next(csvReader) 

以下是使用CSV模块写它的简明方式:

import csv 
from operator import itemgetter 

name_lat_lon = itemgetter(1, 5, 6) 

with open('store_locations.csv') as infile, open('store_coords.csv', 'w') as outfile: 
    csv.writer(outfile).writerows(name_lat_lon(row) for row in csv.reader(infile)) 

更简洁仍然:

import csv 

with open('store_locations.csv') as infile, open('store_coords.csv', 'w') as outfile: 
    csv.writer(outfile).writerows((row[1], row[5], row[6]) for row in csv.reader(infile)) 

甚至更​​多,所以如果某些假设,关于CSV分隔符言:

with open('store_locations.csv') as infile, open('store_coords.csv', 'w') as outfile: 
    outfile.writelines(','.join((row[1], row[5], row[6])) for row in (line.split(',') for line in infile)) 
+0

谢谢你们的回应,我发现在另一个线程 – Blake

+0

一个超级简单的解决方案感谢您的解决方案寿它没有解决我的代码:) – Blake

+0

@Blake:没问题。我怀疑你的“超级简单解决方案”比这个更好或更容易。 – mhawke