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

# 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 

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

関連する問題