Chapter 7. Hashes
Étude 7-1: Creating a HashDict from a File
Your local college has given you a text file that contains data about which courses are taught in which rooms. Here is part of the file. The first column is the course ID number. The second column is the course name, and the third column is the room number.
64850,ENGL 033,RF141 64851,ENGL 080,SC103 64853,ENGL 102,C101B
Your job in this étude is to read the file and create a HashDict
whose key is the room number and whose value is a list of all the courses taught in that room.
Opening Files
To open file test.csv, which you will find in the example download area at URL goes here, use File.open/2
, which takes the path to a file as its first argument and a list of options as its second argument. Here is a shell session that opens the file, reads one line, and then closes the file.
iex(1)> {result, device} = File.open("courses.csv", [:read, :utf8]) {:ok,#PID<0.39.0>} iex(2)> data = IO.readline(device) "64850,ENGL 033,RF141\n" iex(3)> File.close(device) :ok
If you successfully open the file, result
will be :ok
, and the device
will be the variable you when reading or closing the file. If there is some error, result
will be :error
, and the device
variable will contain the reason that the file open failed.
IO.readline/1
reads a line from the file (including the ending \n
character) unless there is no more data, in which case you will get the atom :eof
.
Note
If you do not use the :utf8
option, the file will open in binary mode, and you will ...
Get Études for Elixir now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.