将csv文件转换为另一个选择特定列python的csv

时间:2016-10-24 02:31:15

标签: python list csv

我正在尝试使用以下列转换csv文件:

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

我想创建一个只有Name,Lat,Lon列的新csv,但是我得到了这个错误: header = csvReader.next() AttributeError:'_csv.reader'对象没有属性'next'

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

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='')

感谢任何反馈

1 个答案:

答案 0 :(得分: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))