Friday, August 21, 2015

Working with CSV file in Python

Python has CSV(Comma Separated Values) module which can be imported when working with csv file. Here in the below program I first created a txt file and then copy the content of the file to the csv file for your understanding. You can get user input and put them directly to CSV file too.
First of all learn some basics about the csv module. Open your IDLE and import csv module and the write dir(csv) to see all the processes embedded with this module -
>>> import csv
>>> dir(csv)
['Dialect', 'DictReader', 'DictWriter', 'Error', 'QUOTE_ALL', 'QUOTE_MINIMAL', 'QUOTE_NONE', 'QUOTE_NONNUMERIC', 'Sniffer', 'StringIO', '_Dialect', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__version__', 'excel', 'excel_tab', 'field_size_limit', 'get_dialect', 'list_dialects', 're', 'reader', 'reduce', 'register_dialect', 'unregister_dialect', 'writer']


Please visit the site https://docs.python.org/2/library/csv.html  for detailed discussions of every processes described here. Though some of them is self explanatory and you can always use help(csv.processname) for more informations e.g. >>> help(csv.Dialect)
As this is just a basic program for inputting data to a csv file , I will restrict myself to some basic procedures.
Lets move on to the program;in the program I opened a text file and got some user inputs to the file. I now then open the file again in read mode and extract data from the file. Then I feed the data to a csv file I created in the next part of the program. The program needs many modifications which I have not done intently as I want the readers to modify the program.

#create a csv file with the help of a txt file  -
import csv #importing the csv module
f=open("atextfile.txt",'w')  #opening a file in read mode
entry="" #an empty string
while entry.upper()!='QUIT': #getting user input unless he types 'quit'
    entry=str(raw_input('Write something to file in a Name, age format')) #have the input in entry
    if entry=='quit' or QUIT:
        break #break from loop if quit pressed
    else:
        f.write(str(entry)+'\n') #writing the entry to the file with a new line after each entry
f.close() #closing the file for saving the values  

f=open('atextfile.txt','r') #opening the file again in read mode
data=f.readlines() #readine the data line by line
print data

with open ('anewfile.csv','w') as csvfile: #created a csv file and say it csvfile in the program
    writer=csv.writer(csvfile,delimiter='\n', quoting=csv.QUOTE_ALL) #this is the default csv writer. we have the csv file name, the delimiter which is in our case is newline character and quoting to say to quote all the inputs, don't care if the value is numeric or not.
    for line in data: #Getting to each line of the data
        line=line.split() #splitting the data by white space
       # print line
        writer.writerow(line) #write line to csv file as row basis
    csvfile.close() #closing the file
    print "Successfully Done"
f=open('anewfile.csv','r') #Opening the csv file
rows=csv.reader(f) #read the content to rows
for line in rows : #display each row
    print line


There are many flaws in the program, the main one is that it will not write name and address in a same row, rather it will create a new row for each of the element. Rectifying the problem needs some basic formatting and I will cover that up in my upcoming blog entry.

This program is a basic csv writer , the formatting of rows is not done here. I will do it in the upcoming programs. But it will give you a basic idea about the csv file operations. Peruse through the link I have given above and also go to idle help option to know more about or you can always wait for my next blog entry.

No comments:

Post a Comment

Feautured Post

Python Trivia Post: enumerate()

Python has a very useful inbuilt function, which is called enumerate(). This is needed whenever you need the numbering of a certain element...