2016-10-24 63 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