Reputation: 343
Im beginner and im trying to read files of a folder calles "papers"(you can see the tree of my project in the attached file). Im using this code for do it:
module LeerDocumentos2 where
import System.Directory
import System.IO.Unsafe
import System.IO()
import Documento
reader :: IO [Documento]
reader = do
setCurrentDirectory "papers"
directorio <- getCurrentDirectory
putStrLn directorio -- Directorio donde estan los documentos
pathFicheros <- getDirectoryContents directorio
printAll pathFicheros
return (leerDocumentos pathFicheros)
printAll xs = if null xs -- If the list is empty
then return () -- then we're done, so we quit.
else do print (head xs) -- Otherwise, print the first element
printAll (tail xs) -- then print all the other elements.
leerDocumentos :: [FilePath] -> [Documento]
leerDocumentos [] = []
leerDocumentos (x:xs) = do
let documento = unsafePerformIO (leerDocumento x)
[documento]++ leerDocumentos xs
leerDocumento :: String -> IO Documento
leerDocumento ruta = do
putStrLn ruta
texto <- readFile ruta
let docuAux = lines texto
let revista = obtenerRevista docuAux
let idd = obtenerID docuAux
let anno = obtenerAnno docuAux
let titulo = obtenerTitulo docuAux
let resumen = obtenerResumen docuAux
let secciones = obtenerSecciones docuAux
let documento = D (revista,idd,anno,titulo,resumen,secciones)
return documento
obtenerRevista :: [String] -> String
obtenerRevista [] = []
obtenerRevista texto = head texto
obtenerID:: [String] -> String
obtenerID [] = []
obtenerID texto = head (drop 1 (texto))
obtenerAnno:: [String] -> String
obtenerAnno [] = []
obtenerAnno texto = head (drop 2 (texto))
obtenerTitulo:: [String] -> String
obtenerTitulo [] = []
obtenerTitulo texto = head (drop 4 (texto))
obtenerResumen:: [String] -> String
obtenerResumen [] = []
obtenerResumen texto = head (drop 6 (texto))
obtenerSecciones :: [String]->[String]
obtenerSecciones [] = []
obtenerSecciones texto = quitarSeparador (drop 8 (texto))
quitarSeparador :: [String] -> [String]
quitarSeparador [] = []
quitarSeparador (s:sn) = if s == "--" || length s <= 1 then --Para quitar lineas blancas
quitarSeparador sn
else
s:quitarSeparador sn
but im having the next error:
*** Exception: .: openFile: inappropriate type (is a directory)
Someone can help me please?
Upvotes: 0
Views: 241
Reputation: 52039
Again, don't use unsafePerformIO
.
I bet your problem is that getDirectoryContents
returns .
and ..
which are directories.
At the very least I would filter those out. If the directory has any sub-directories you will also need to filter those out.
Also, I would become familiar with Control.Monad. Try something like this:
import Control.Monad (forM)
import Data.List (isPrefixOf)
reader = do setCurrentDirectory ...
paths <- getDirectoryContents dir
let files = filter (not . isPrefixOf ".") paths
forM files $ \file -> do
putStrLn $ "processing " ++ file
leerDocumento file
Now you can get rid of unsafePerformIO
and leerDocumentos
.
Upvotes: 2