How to add elements in a .csv file in python

0

I'm having a hard time creating an algorithm that adds a third-row element to the CSV file in the Python language.

The file has the following data:

   Serial;             Imei;           Número;       Icc;         Stock
869606020314526;   869606020314526;  934097609;  20000736862016;  Stock

The idea is to enter the number +244 in each beginning of the number, being: +244934097609

    
asked by anonymous 09.08.2018 / 20:19

1 answer

0

Hi, there are two ways to do this, the most elegant and using a library for python called "pandas" this is the link for their site, you can install using the python pip and have all the documentation on their site.

But I'm going to write a less elegant way here, but it solves your problem.

Entry: data.csv

Serial; Imei; Número; Icc; Stock 
869606020314526; 869606020314526; 934097609; 20000736862016; Stock

Script: numeroUpdate.py

file_in = open('data.csv','r')
file_out = open('numero_atualizado.csv','w+')

next(file_in) # Pois queremos pular a primeira linha.
file_out.write('Serial; Imei; Número; Icc; Stock\n') # Cabeçario do arquivo, e o "\n" é para pular de linha.

string = '' # Criado para podermos chamar o metodo join.

for line in file_in:
    line = line.split('; ') # No split, cortamos string. 
    numero = "+244" + line[2]
    line[2] = numero
    file_out.write(string.join(line))

file_out.close()

I think it can help, anything, just comment.

    
16.08.2018 / 01:19