[Haskell-cafe] implementing a csv reader

Henk-Jan van Tuyl hjgtuyl at chello.nl
Wed Aug 23 15:37:14 EDT 2006


Reading and writing a comma seperated datafile doesn't have to be that  
complicated; the following is an easy way to read a CSV file into a list  
of tuples and display the list on screen:

> displayTuples =
>   do
>    csvData <- readFile "data.csv"
>    putStrLn $ unlines $ map (show . readTuple) $ lines csvData

> readTuple :: String -> (Int, Bool, String)
> readTuple line = read tuple
>   where    tuple = '(' : line ++ ")"

If the file "data.csv" contains the following:
   1, True, "Festina lente"
   2, False, "Carpe diem"

displayTuples displays:
   (1,True,"Festina lente")
   (2,False,"Carpe diem")

Writing a list of tuples to a CSV file is even simpler:

> writeTuples file tuples =  writeFile file $ unlines $ map (tail . init .  
> show) tuples

The call:
   writeTuples "new.csv" [(1, 'a'), (2, 'b')]
results in a file containg:

(without the leading spaces)

Met vriendelijke groet,
Henk-Jan van Tuyl


On Tue, 22 Aug 2006 11:19:35 +0200, Tamas K Papp <tpapp at Princeton.EDU>  

> Hi,
> Now that I have read the tutorials, I think that the best way to learn
> Haskell would be to use the language and write something simple yet
> useful.  I noticed that Haskell lacks a module for reading/writing csv
> (comma separated value) files, so I thought I could implement that.
> Questions:
> 1. Please tell me if you know of a csv module, because then I would do
>    something else.
> 2. I am looking for a parser, but I don't know Haskell parsers.  Is
>    Parsec a good choice?
> Thanks,
> Tamas

Using Opera's revolutionary e-mail client:

More information about the Haskell-Cafe mailing list