Wednesday, 25 January 2017

WORKING WITH CSV FILES IN PYTHON AND REPLACING TEXT IN EXISTING FILE AND SAVE THE DATA IN OTHER FILE

In order to work with the CSV files we use built-in module called as csv. In order to read or write or modify the data of the csv file we need to implement following steps –
1. open the file in required mode
2. create the csv file represented object.
3. read or write or update the data
4. close the file

Example –
import csv
f1=open("demo.csv")
print f1
csvreader = csv.reader(f1)
print csvreader
data = list(csvreader)
for line in data:
    for word in line:
        print word,
    printf1.close()

Output –
<open file 'demo.csv', mode 'r' at 0x022ED1D8>
<_csv.reader object at 0x02479930>
Name Class Semester
Rakesh MCA VI
Barsha MCA VI
Harry Btech VII
Bikash MCA VI

Example –
import os
import string
def replace(file,search_for,replace_with):
    temp = os.path.splitext(file)[0]+".tmp"
    try :
        os.remove(temp)
    except os.error:
        pass
    fi=open(file)
    fo=open(temp,"w")
    for s in fi.readlines():
        fo.write(string.replace(s,search_for,replace_with))
    fi.close()
    fo.close()
file="abc.txt"
replace(file,"bamunimaidam","barnachalpath")

Output –
abc.tmp
rakesh kumar prasad
barnachalpath, guwahati-21
assam
+918011807550

No comments:

Post a Comment