Home > Enterprise >  problem to export to a csv file with a loop
problem to export to a csv file with a loop

Time:04-13

I have a python program where I have to export all the data from a csv file line by line. I managed to extract the data and make the loop. but I can't manage to export the processed data (coordinates) on another csv file. here is the code and an extract of the csv file I have. would you have a solution and/or improvements :)

ps: i know it's really not clean only god knows how it works

Pyton :

import pandas as pd
import csv
import geocoder
from geopy.geocoders import Nominatim

f = open('Data-nom.csv', 'r')
NumberOfLine = 0
for line in f:
    NumberOfLine  = 1
print('Nombre de lignes: ',NumberOfLine)
e = 0
d = 0
while d < 20464 :
    e  = 1
    with open('Data-nom.csv', 'r') as file:
        val = list(csv.reader(file))[e]
        print(val)
        x = val
        geolocator = Nominatim(user_agent="test")
        location = geolocator.geocode(x)
    print(location.address)
    latlong = (location.latitude, location.longitude)
    print(latlong)
    with open('out.csv', 'w', newline = '') as csvfile:
        my_writer = csv.writer(csvfile, delimiter = ' ')
        my_writer.writerow(latlong)
    d  = 1


CSV :

2 RUE FLAMENG CLERMONT FERRAND 63000
12 CITE DE LA MONTADE AURILLAC 15000
37 BOULEVARD JOSEPH ROSSELLI BELLEVILLE 69220
1 AVENUE DE LA RESISTANCE MONTREUIL 93100
AVENUE DE LINGENFELD TORCY 77200
70 RUE LEON FROT PARIS 75011

CodePudding user response:

Open the files once; read/process each line of the input file, then write that processed data to the output file...

algorithm/pseudocode

with open('Data-nom.csv', 'r') as file, open('out.csv', 'w', newline = '') as csvfile:
   for each line in file:
       # get the lat and lon from the line
       # write the lat,lon to the csvfile

CodePudding user response:

I believe this does what you want, more sensibly, with no pandas and no CSV. Neither of your files are CSV files. They're just text files.

import geocoder
from geopy.geocoders import Nominatim

outfile = open('out.csv', 'w')
for row in open('Data-nom.csv'):
    location = geolocator.geocode(row)
    print(location.address)
    latlong = (location.latitude, location.longitude)
    print( f"{location.latitude} {location.longitude}", file=outfile)
  • Related