How to concatenate value to a column of a table in csv?

Asked

Viewed 445 times

2

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

The file has following data:

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

The idea is to insert the number +244 in each beginning of the number, leaving: +244934097609

  • You can share what you’ve tried, the code and the specific error you’ve stumbled into?

  • If one of the answers below solved your problem and there was no doubt left, choose the one you liked the most and mark it as correct/accepted by clicking on the " " that is next to it, which also marks your question as solved. If you still have any questions or would like further clarification, feel free to comment.

2 answers

2


Solution using pandas:

import pandas as pd 

df=pd.read_csv("file.csv", sep=";")
df.columns=[k.strip() for k in df.columns]
df['Número']=['+244'+str(k) for k in df["Número"]]

print(df)

Returns:

            Serial             Imei         Número             Icc    Stock
0  869606020314526  869606020314526  +244934097609  20000736862016    Stock

Saving:

df.to_csv("file.csv", index=False)
  • 1

    Good solution! + 1

  • I’ve never used pandas, but I’ll test your example

1

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 website, it has how to install using python’s "Pip" and has all documentation on their website.

But I’ll write you a less elegant way, but it solves your problem.

Input : 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 might help, anything, just comment.

  • When running it displays the following error: line 11, in <module> line[2] = numero Typeerror: str' Object does not support item assignment >>> strings are immutable in Python

Browser other questions tagged

You are not signed in. Login or sign up in order to post.