简体   繁体   中英

converting csv file to another csv choosing specific columns python

i am trying to convert a csv file with the following columns:

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

I want to make a new csv with only the Name, Lat, Lon columns but im getting this error: header = csvReader.next() AttributeError: '_csv.reader' object has no attribute 'next'

here is my code so far:

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

thanks for any feedback

That code will work in Python 2, ie csv.reader objects have a next() method. However, in Python 3 there is no such method.

Instead, and this works in both versions of Python, use 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)

Here is a concise way of writing it using the csv module:

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

More concise still:

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

Or even more so if certain assumptions are made about the CSV delimiter:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM