Python 2.7 code for Replacing whole value of a column in a csv file -


i have data imported sql server in csv file headers.

i want write **code in python2.7 ** can read csv file , re-write new csv file in have masked last 2 columns regex 'secret value'.

sample input of csv:

id,name,city,ssn,creditcardno 1,joy,london,123-465-456,123456789087645 2,sam,newyork,765-465-457,98765434567345 3,jhon,paris,678-365-654,765654542345677 4,eric,delhi,456-888-999,123456789087645 

expected sample output:

id,name,city,ssn,creditcardno 1,joy,london,secret value,secret value 2,sam,newyork,secret value,secret value 3,jhon,paris,secret value,secret value 4,eric,delhi,secret value,secret value 

my attempt:

import sys import csv  r = csv.reader(open('c:\\users\\praveen\\workspace\\samplefiles\\test1.csv')) lines = [l l in r]  lines[2][2] = '30'  writer = csv.writer(open('c:\\users\\praveen\\workspace\\samplefiles\\test4.csv', 'wb')) writer.writerows(lines) 

this changes 1 element only, want whole column masked.

i think need read_csv first, replace values iloc , last write file dataframe.to_csv:

import pandas pd pandas.compat import stringio  temp=u"""id,name,city,ssn,creditcardno 1,joy,london,123-465-456,123456789087645 2,sam,newyork,765-465-457,98765434567345 3,jhon,paris,678-365-654,765654542345677 4,eric,delhi,456-888-999,123456789087645""" #after testing replace 'stringio(temp)' 'filename.csv' df = pd.read_csv(stringio(temp)) print df    id  name     city          ssn     creditcardno 0   1   joy   london  123-465-456  123456789087645 1   2   sam  newyork  765-465-457   98765434567345 2   3  jhon    paris  678-365-654  765654542345677 3   4  eric    delhi  456-888-999  123456789087645  df.iloc[:, -2:] = 'secret value' print df    id  name     city           ssn  creditcardno 0   1   joy   london  secret value  secret value 1   2   sam  newyork  secret value  secret value 2   3  jhon    paris  secret value  secret value 3   4  eric    delhi  secret value  secret value  df.to_csv('file.csv', index=false) 

Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -