Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use delimiter for csv in python

I'm having trouble with figuring out how to use the delimiter for csv.writer in Python. I have a csv file in which the strings separated by commas are in single cell and I need to have each word in each individual cell. For ex:

   100 , 2559   ,,Main, St,LEOMA,LEOMA,498,498, AK,AK    140 , 425    ,,Main, St,LEOMA,LEOMA,498,498, AK,AK    100 , 599    ,,Main, St,LEOMA,LEOMA,498,498, AK,AK 

should be

   100  2559        Main    St  LEOMA   LEOMA   498 498 AK  AK    140  425     Main    St  LEOMA   LEOMA   498 498 AK  AK    100  599     Main    St  LEOMA   LEOMA   498 498 AK  AK 

(each word in individual cell).

I tried:

import csv workingdir = "C:\Mer\Ven\sample" csvfile = workingdir+"\test3.csv" f=open(csvfile,'wb')  csv.writer(f, delimiter =' ',quotechar =',',quoting=csv.QUOTE_MINIMAL) 
like image 454
hydi Avatar asked May 29 '13 20:05

hydi


People also ask

How do I use delimiter in Python CSV?

Optional Python CSV reader Parametersdelimiter specifies the character used to separate each field. The default is the comma ( ',' ). quotechar specifies the character used to surround fields that contain the delimiter character. The default is a double quote ( ' " ' ).


2 Answers

Your code is blanking out your file:

import csv workingdir = "C:\Mer\Ven\sample" csvfile = workingdir+"\test3.csv" f=open(csvfile,'wb') # opens file for writing (erases contents) csv.writer(f, delimiter =' ',quotechar =',',quoting=csv.QUOTE_MINIMAL) 

if you want to read the file in, you will need to use csv.reader and open the file for reading.

import csv workingdir = "C:\Mer\Ven\sample" csvfile = workingdir+"\test3.csv" f=open(csvfile,'rb') # opens file for reading reader = csv.reader(f) for line in reader:     print line 

If you want to write that back out to a new file with different delimiters, you can create a new file and specify those delimiters and write out each line (instead of printing the tuple).

like image 56
underrun Avatar answered Oct 01 '22 12:10

underrun


ok, here is what i understood from your question. You are writing a csv file from python but when you are opening that file into some other application like excel or open office they are showing the complete row in one cell rather than each word in individual cell. I am right??

if i am then please try this,

import csv  with open(r"C:\\test.csv", "wb") as csv_file:     writer = csv.writer(csv_file, delimiter =",",quoting=csv.QUOTE_MINIMAL)     writer.writerow(["a","b"]) 

you have to set the delimiter = ","

like image 39
abhishekgarg Avatar answered Oct 01 '22 12:10

abhishekgarg