Lecture 15. Files


Persistence

Most of the programs we have seen so far are transient in the sense that they run for a short time and produce some output, but when they end, their data disappears. If you run the program again, it starts with a clean slate.

Other programs are persistent: they run for a long time (or all the time); they keep at least some of their data in permanent storage (a hard drive, for example); and if they shut down and restart, they pick up where they left off.

Examples of persistent programs are operating systems, which run pretty much whenever a computer is on, and web servers, which run all the time, waiting for requests to come in on the network.

One of the simplest ways for programs to maintain their data is by reading and writing text files. We have already seen programs that read text files; in this chapter we will see programs that write them.

An alternative is to store the state of the program in a database. In this chapter I will present a module, JLD, that makes it easy to store program data.

Reading and writing

A text file is a sequence of characters stored on a permanent medium like a hard drive, flash memory, or CD-ROM.

To write a file, you have to open it with mode "w" as a second parameter:


In [1]:
fout = open("output.txt", "w")


Out[1]:
IOStream(<file output.txt>)

If the file already exists, opening it in write mode clears out the old data and starts fresh, so be careful! If the file doesn’t exist, a new one is created.

open returns an IOStream object that provides methods for working with the file. The write method puts data into the file:


In [2]:
line1 = "This here's the wattle,\n"
write(fout, line1)


Out[2]:
24

When you are done writing, you should close the file.


In [3]:
close(fout)

If you don’t close the file, it gets closed for you when the program ends.

Formatting

The print(ln) family of functions can also be used with as first argument the


In [4]:
fout = open("output.txt", "w")
x = 150
println(fout, "The best promotion is $(x)!")
close(fout)

The @printf macro prints arguments with the C style format specification string


In [5]:
@printf("Color %s, number1 %d, number2 %05d, hex %#x, float %5.2f, unsigned value %u.\n",
       "red", 123456, 89, 255, 3.14159, 250);


Color red, number1 123456, number2 00089, hex 0xff, float  3.14, unsigned value 250.

Filenames and paths

Files are organized into directories (also called “folders”). Every running program has a “current directory”, which is the default directory for most operations. For example, when you open a file for reading, Python looks for it in the current directory.

The function pwd returns the name of the current directory:


In [6]:
pwd()


Out[6]:
"/home/jupyter/ES123/Lectures"

A string like "/home/jupyter/ES123/Lectures" that identifies a file or directory is called a path.

A simple filename, like "output.txt" is also considered a path, but it is a relative path because it relates to the current directory. If the current directory is "/home/jupyter", the filename "output.txt" would refer to "/home/jupyter/output.txt".

A path that begins with '/ ' does not depend on the current directory; it is called an absolute path.

Julia provides other functions for working with filenames and paths. For example, ispath checks whether a file or directory exists:


In [7]:
ispath("ouptut.txt")


Out[7]:
false

If it exists, isdir checks whether it’s a directory:


In [8]:
isdir("output.txt")


Out[8]:
false

Similarly, isfile checks whether it’s a file.

readdir returns a list of the files (and other directories) in the given directory:


In [9]:
readdir(pwd())


Out[9]:
23-element Array{String,1}:
 ".ipynb_checkpoints"                                    
 "Lecture 0. Introduction.ipynb"                         
 "Lecture 10. Strings.ipynb"                             
 "Lecture 11. Arrays.ipynb"                              
 "Lecture 12. Dictionaries.ipynb"                        
 "Lecture 13. Tuples.ipynb"                              
 "Lecture 14. Data structure selection.ipynb"            
 "Lecture 15. Files.ipynb"                               
 "Lecture 16. Types and Objects.ipynb"                   
 "Lecture 17. Types and Functions.ipynb"                 
 "Lecture 18. Methods.ipynb"                             
 "Lecture 19. Abstract types.ipynb"                      
 "Lecture 1. Software-Hardware Interface.ipynb"          
 "Lecture 2. Computer Representation of Data.ipynb"      
 "Lecture 3. The Way of the Program.ipynb"               
 "Lecture 4. Problem Solving.ipynb"                      
 "Lecture 5. Variables, Expressions and Statements.ipynb"
 "Lecture 6. Functions.ipynb"                            
 "Lecture 7. Conditionals and Recursion.ipynb"           
 "Lecture 8. Fruitful Functions.ipynb"                   
 "Lecture 9. Iteration.ipynb"                            
 "output.txt"                                            
 "wc.jl"                                                 

To demonstrate these functions, the following example “walks” through a directory, prints the names of all the files, and calls itself recursively on all the directories.


In [10]:
function walk(dirname)
    for name in readdir(dirname)
        path = joinpath(dirname, name)
        if isfile(path)
            println(path)
        else
            walk(path)
        end
    end
end


Out[10]:
walk (generic function with 1 method)

In [11]:
walk("/home/jupyter/ES123")


/home/jupyter/ES123/Assignments/Assignment 1. Variables, Expressions, Statements and Functions.ipynb
/home/jupyter/ES123/Assignments/Assignment 2. Conditionals and Recursion.ipynb
/home/jupyter/ES123/Assignments/Assignment 3. Fruitful Functions and Iteration.ipynb
/home/jupyter/ES123/Assignments/Assignment 4. Strings.ipynb
/home/jupyter/ES123/Assignments/Assignment 5. Arrays, Dictionaries and Tuples.ipynb
/home/jupyter/ES123/Assignments/Assignment 6. Files.ipynb
/home/jupyter/ES123/Assignments/Assignment 7. Types and Methods.ipynb
/home/jupyter/ES123/Assignments/.ipynb_checkpoints/Assignment 1. Variables, Expressions, Statements and Functions-checkpoint.ipynb
/home/jupyter/ES123/Assignments/.ipynb_checkpoints/Assignment 2. Conditionals and Recursion-checkpoint.ipynb
/home/jupyter/ES123/Assignments/.ipynb_checkpoints/Assignment 3. Fruitful Functions and Iteration-checkpoint.ipynb
/home/jupyter/ES123/Assignments/.ipynb_checkpoints/Assignment 4. Strings-checkpoint.ipynb
/home/jupyter/ES123/Assignments/.ipynb_checkpoints/Assignment 5. Arrays, Dictionaries and Tuples-checkpoint.ipynb
/home/jupyter/ES123/Assignments/.ipynb_checkpoints/Assignment 6. Files-checkpoint.ipynb
/home/jupyter/ES123/Assignments/.ipynb_checkpoints/Assignment 7. Types and Methods-checkpoint.ipynb
/home/jupyter/ES123/data/emma.txt
/home/jupyter/ES123/data/words.txt
/home/jupyter/ES123/.git/COMMIT_EDITMSG
/home/jupyter/ES123/.git/config
/home/jupyter/ES123/.git/description
/home/jupyter/ES123/.git/FETCH_HEAD
/home/jupyter/ES123/.git/HEAD
/home/jupyter/ES123/.git/hooks/applypatch-msg.sample
/home/jupyter/ES123/.git/hooks/commit-msg.sample
/home/jupyter/ES123/.git/hooks/fsmonitor-watchman.sample
/home/jupyter/ES123/.git/hooks/post-update.sample
/home/jupyter/ES123/.git/hooks/pre-applypatch.sample
/home/jupyter/ES123/.git/hooks/pre-commit.sample
/home/jupyter/ES123/.git/hooks/prepare-commit-msg.sample
/home/jupyter/ES123/.git/hooks/pre-push.sample
/home/jupyter/ES123/.git/hooks/pre-rebase.sample
/home/jupyter/ES123/.git/hooks/pre-receive.sample
/home/jupyter/ES123/.git/hooks/update.sample
/home/jupyter/ES123/.git/index
/home/jupyter/ES123/.git/info/exclude
/home/jupyter/ES123/.git/logs/HEAD
/home/jupyter/ES123/.git/logs/refs/heads/master
/home/jupyter/ES123/.git/logs/refs/remotes/origin/HEAD
/home/jupyter/ES123/.git/logs/refs/remotes/origin/master
/home/jupyter/ES123/.git/objects/01/86389cd5b1e823b8a84c086cda766d7c1ec217
/home/jupyter/ES123/.git/objects/02/928bbe11b69c013f7a04121ace966e5d0e4852
/home/jupyter/ES123/.git/objects/03/68790213744c62d0759a8ce5400f3e9acc2f4e
/home/jupyter/ES123/.git/objects/03/da196d0dd63e4c165f6354d4ece6d76c8c9804
/home/jupyter/ES123/.git/objects/05/badc0ba9f3e9260f0961e0d90327fa75011e8f
/home/jupyter/ES123/.git/objects/06/20d4eb6c2e80e2233abb8eb385fbcb8ad06af9
/home/jupyter/ES123/.git/objects/06/31db9eb480f4cd81a92a07cdf1ddee1fd9c823
/home/jupyter/ES123/.git/objects/06/622c1e359d408b15c24f8319e2c19d4ff28f57
/home/jupyter/ES123/.git/objects/06/72d6400e7dbdd1b4b78b51113fb255e3564779
/home/jupyter/ES123/.git/objects/06/a6c561f946434c5edce17a62a9563ade28f8d6
/home/jupyter/ES123/.git/objects/06/cf19f2a6aa8c6f6732bb5d5eeaacd5742b5375
/home/jupyter/ES123/.git/objects/07/bed5ae81a8ed45b2e245ca67009849d25e8d56
/home/jupyter/ES123/.git/objects/09/29262c3218d8c39c11a608011b9e0938f8e11b
/home/jupyter/ES123/.git/objects/0a/b00807a6b732537540f062025912dcfa24c54e
/home/jupyter/ES123/.git/objects/0c/992f0796057cc225bae48def783302820f7407
/home/jupyter/ES123/.git/objects/0d/f07ca1d4f37768aee03cd71041ee1662e18ee2
/home/jupyter/ES123/.git/objects/0e/b3faf9556f1b60eccaa362435bcd3890e53794
/home/jupyter/ES123/.git/objects/0f/422d800bb2db6d7d12a0381a7ea3b4b3c4493b
/home/jupyter/ES123/.git/objects/0f/f9f751edaaa11bfca17ef91c4ad33b30edfabb
/home/jupyter/ES123/.git/objects/11/af76f501e93a622c9a6f69d641993b36a8b4f6
/home/jupyter/ES123/.git/objects/12/0fcea14e90d71c9995425adf9d2f2d1a294268
/home/jupyter/ES123/.git/objects/12/2af2ba57df8e2120c44df515cee42da8c0fffc
/home/jupyter/ES123/.git/objects/12/4c7d666e3e3298f46e21211cef8b11facbfb72
/home/jupyter/ES123/.git/objects/12/d17af8be67966a812baa1cc0598faffa1ae263
/home/jupyter/ES123/.git/objects/15/03541533aecb6b27d4675f2f0ac20358bbda96
/home/jupyter/ES123/.git/objects/15/b24e1bc755cfb5ae59839ea3c6ac8f37dfab33
/home/jupyter/ES123/.git/objects/16/4f4b6fd3955326ccaefa7c0f66c6a9658b7bbb
/home/jupyter/ES123/.git/objects/17/2337509c15e1e09ebd364e2613f3bc8cd93402
/home/jupyter/ES123/.git/objects/17/6e5e9ead0e3783b90d0cbea1f9e4230ca2298f
/home/jupyter/ES123/.git/objects/18/976cd6bf0f33ffe6b83fa20415be47e548178d
/home/jupyter/ES123/.git/objects/19/f46a3fdf567fd7d80b1247aa6302125f7a7acf
/home/jupyter/ES123/.git/objects/1b/fb7eb3eacfec6a95fc98dc7198aae9bccd4eaa
/home/jupyter/ES123/.git/objects/1d/7e6a1d9f32aea9b90f73aa471b3b11cdd494e4
/home/jupyter/ES123/.git/objects/1d/aa7ed29268abb7817a311200c4f3b8d222eb5e
/home/jupyter/ES123/.git/objects/1f/882b5712697e128713090e2a9203883c403140
/home/jupyter/ES123/.git/objects/21/c1ec98fac2c0aeeebf0081fc70785c734b4938
/home/jupyter/ES123/.git/objects/22/66aa8eafa49032a1ac3074738f5ff11fa8d2a1
/home/jupyter/ES123/.git/objects/23/2f60d494d45456821fac5753a7db239e04f790
/home/jupyter/ES123/.git/objects/23/586dca4a9390efb4a4baa9e5133c0ab8f684d3
/home/jupyter/ES123/.git/objects/24/2dd85c5958b7fd2dfae08590363645a872db24
/home/jupyter/ES123/.git/objects/26/088762c238eaa6ea64ea3f361d3b78f2e05537
/home/jupyter/ES123/.git/objects/26/10ecea34284fddcac0b60658f9ffc384726e45
/home/jupyter/ES123/.git/objects/26/b35fd9476df4e8cd36770454998de356c769f3
/home/jupyter/ES123/.git/objects/27/f6896f434cbdf14f5190fe61f60fa248f32734
/home/jupyter/ES123/.git/objects/28/8cf3bb7fe2c7bb867b4923e4f31c82980b32f5
/home/jupyter/ES123/.git/objects/28/9dc73720b1753df4caa5a96901320c75677f66
/home/jupyter/ES123/.git/objects/29/1b60c84d5a435a5d9367fe9fc0f543dc3ff95c
/home/jupyter/ES123/.git/objects/2a/878659ece86830f1d5d4afe7ce65809ff5499c
/home/jupyter/ES123/.git/objects/2b/49c94b4cd7f1b3aa8fd637db4faa1bc867bd2a
/home/jupyter/ES123/.git/objects/2b/c1c4698b67acb1b358494c8b8e21b6b548e92e
/home/jupyter/ES123/.git/objects/2c/e41524ae3bed61876a76c782bd128e984c3f57
/home/jupyter/ES123/.git/objects/2d/abe1f039148bad063982fecc5b7c94c7208c57
/home/jupyter/ES123/.git/objects/2f/5a00c471977b35c631021e78295b817d0f6357
/home/jupyter/ES123/.git/objects/30/60aae86e79a41ba3e04d7e25869c42c76074f0
/home/jupyter/ES123/.git/objects/31/3972b3f274f15b739bcfb8f2ba82015d7dabdd
/home/jupyter/ES123/.git/objects/31/ad3a00484c551ddcb7efaa0be28ea3337f4c49
/home/jupyter/ES123/.git/objects/36/257c099b31b372a6c4c8d831ed0d8c22b24cf1
/home/jupyter/ES123/.git/objects/37/8aec5eddd0be247d815f1560cebfc6682ee7b1
/home/jupyter/ES123/.git/objects/37/b6e1735f15c290f5e5e35a36ec697b7c2a3821
/home/jupyter/ES123/.git/objects/38/54572fd7ab741958c1b1a4ea3781a07d72b3df
/home/jupyter/ES123/.git/objects/38/ae056a4d7f440fded9e80d55c931366bdc3eae
/home/jupyter/ES123/.git/objects/39/037b1279f8862b48f67a2c2dc37f2633ba998f
/home/jupyter/ES123/.git/objects/39/0f55adb3be15084def363bf72920ccb72cefa8
/home/jupyter/ES123/.git/objects/3a/887d0893e55c05a3877d983da3ea6ec19c8f36
/home/jupyter/ES123/.git/objects/3d/b35530968d9498be91951d5cef12d7b7b152df
/home/jupyter/ES123/.git/objects/3f/d49a64960b8fcabde0c8920d49fd6310515052
/home/jupyter/ES123/.git/objects/42/916abbdb2d1ae55a59c1bca11ee81df3d7f1ed
/home/jupyter/ES123/.git/objects/43/1568da07d8ffc4c1d7c27e562e2008f593bf67
/home/jupyter/ES123/.git/objects/43/921f26b74ad24b9686cb17bd99f72ca2c88bd7
/home/jupyter/ES123/.git/objects/44/ebf80c3bda2a336d3f0abb996997455a75bf65
/home/jupyter/ES123/.git/objects/45/55ec6c2a7321e1464304d9805ba8ecef006996
/home/jupyter/ES123/.git/objects/46/e4a7d89ba1a51127f90757303237426a7a7a48
/home/jupyter/ES123/.git/objects/47/3d96c2ce3c7537dacc78cefd2e4e0279192b45
/home/jupyter/ES123/.git/objects/47/75500016395381c9e9379dee244e0f9ef62ba3
/home/jupyter/ES123/.git/objects/48/db68a04d1fda5f2e5b4a965e08252b3eeda273
/home/jupyter/ES123/.git/objects/4c/76dcacd772c416d6ee4eda03d49f0845fd6ab7
/home/jupyter/ES123/.git/objects/4d/d05aed73da81102706d11e7906fe738a31ec2c
/home/jupyter/ES123/.git/objects/4d/d0e64955c97f710e2a1eaf2b2efbb70c98bcbd
/home/jupyter/ES123/.git/objects/4f/494325a092ee1c6c023a6ab8feea6e3109bbd8
/home/jupyter/ES123/.git/objects/50/0a3adc714def00acd213f0d7ebae739de09845
/home/jupyter/ES123/.git/objects/50/313750b54913c3d92a35426e004d197d6b1e1c
/home/jupyter/ES123/.git/objects/51/2f9b53744c086f95fa1a8da02c73dd652b2173
/home/jupyter/ES123/.git/objects/52/45fdffa3640c5a25664649125641a6302da755
/home/jupyter/ES123/.git/objects/52/8439d5015515b90a2cc3eb27d1135f16237db9
/home/jupyter/ES123/.git/objects/54/fccff468194c2ff120969a1665dcc465d20b5a
/home/jupyter/ES123/.git/objects/57/6d1b026d02ad4259ef063f776ef379bfe98cf9
/home/jupyter/ES123/.git/objects/59/ffd0870a79697668d6d202bed81b20934d18ed
/home/jupyter/ES123/.git/objects/5a/d193632f644917b1f5d5131328a196efe48211
/home/jupyter/ES123/.git/objects/5d/7a498b755e1004f82af6613c4bd04461ac28cc
/home/jupyter/ES123/.git/objects/5d/ea7cedfa8abed9a2d5ff101a4091499197daba
/home/jupyter/ES123/.git/objects/5e/06bf197c108fffe3405b3e889eca39c72743d4
/home/jupyter/ES123/.git/objects/5f/add9bd601227c73e1bd6ac2985184d1ce7088b
/home/jupyter/ES123/.git/objects/61/161aa59689506a596799172cb752637ae02fc9
/home/jupyter/ES123/.git/objects/63/052967bd78f3d56d8df6dca680281920b770f2
/home/jupyter/ES123/.git/objects/65/8c464398ba2056596fcda2c7450204386af8be
/home/jupyter/ES123/.git/objects/66/edd39e6003dceb2b47c1ba2fe9124dc09f59da
/home/jupyter/ES123/.git/objects/67/d5e9a8abc9948b3fa4d6aa49c70673141508fb
/home/jupyter/ES123/.git/objects/68/9c2336a625ed421317efd7f2b5587d6d636899
/home/jupyter/ES123/.git/objects/69/781e6bc3ad5b35386da57b347198b92e13f764
/home/jupyter/ES123/.git/objects/6b/58e8c1e666969d9a25376ee846a67815281520
/home/jupyter/ES123/.git/objects/6e/7a5386cb9714b220d528c4bb2506535ec135e6
/home/jupyter/ES123/.git/objects/6f/7cbcedae4466e97f57b19b3e4d5e04b1452e76
/home/jupyter/ES123/.git/objects/6f/c9e7bd38e02d4d6d1a5d61e823d380df203b16
/home/jupyter/ES123/.git/objects/70/f8613b3c6bce991c7ccd7e56ea12c5e75ff310
/home/jupyter/ES123/.git/objects/70/fbd2e1298bad783912fa7bdb2257796ad0f1fa
/home/jupyter/ES123/.git/objects/71/bfde6880e979cb013abc447c15b943a48176bc
/home/jupyter/ES123/.git/objects/71/dd574cfcacf14fb3303cbac772f57d4b8acd82
/home/jupyter/ES123/.git/objects/72/4d495123f86f092127dbe298f9d17ac2690998
/home/jupyter/ES123/.git/objects/72/6e59509e466b5c19bb9095635cb1bd3f50166e
/home/jupyter/ES123/.git/objects/72/b7234bafce2a0448115fd3e90e08e4c7e6bcca
/home/jupyter/ES123/.git/objects/73/bf33dfe101c9172d743d92bf4078bac10beb14
/home/jupyter/ES123/.git/objects/74/88af8fb3162e53702841a1fb4e6f7ce5984b75
/home/jupyter/ES123/.git/objects/76/f0eaa07662d742ded5a0f6008363867e1dc5fd
/home/jupyter/ES123/.git/objects/77/e2db1a4b2d0445a6709136fe94d15e09c1c7c4
/home/jupyter/ES123/.git/objects/78/547759c27cb30f80c63ea4f7352e57ef5d4a98
/home/jupyter/ES123/.git/objects/78/78fca611414100f36c22749b4fa367f5bb6f2a
/home/jupyter/ES123/.git/objects/79/2362c20ba541b9621618894b74fa970a3a83dd
/home/jupyter/ES123/.git/objects/7a/b1149092726428e8c532845ba71a1e64e55ff4
/home/jupyter/ES123/.git/objects/7c/0bcd58273ccd842ac0848674791569759870d9
/home/jupyter/ES123/.git/objects/7c/1d040e4225da0b13be7272f1b3a538d99a8ee5
/home/jupyter/ES123/.git/objects/7c/34ab7d86f375d10e142e2d82f531065af3bca8
/home/jupyter/ES123/.git/objects/7c/59db6e5f2fa373f6a40dbd53e2649b2c46a0b4
/home/jupyter/ES123/.git/objects/7d/03b6b3ac66fc27e2544632978fb199f67bf3fa
/home/jupyter/ES123/.git/objects/7d/1419372e119d0dc4574be765f653fd47b45f87
/home/jupyter/ES123/.git/objects/7d/48717a096801b77c133b836ae6ba7cfd21a4be
/home/jupyter/ES123/.git/objects/7d/a37cc893431ab266f3b1e53af455e14718c50d
/home/jupyter/ES123/.git/objects/7d/c0968e5b2f12f799336387932e867107250b9f
/home/jupyter/ES123/.git/objects/7e/8afb3958c337e1429abfeb3c707287dcf59530
/home/jupyter/ES123/.git/objects/80/9b44d8eddbe3633df730bc89b8659d6ce08c21
/home/jupyter/ES123/.git/objects/81/6a3ba7d591d243525090092d4030c1736180fd
/home/jupyter/ES123/.git/objects/83/0019736a324b700906585a631542c227b5cfae
/home/jupyter/ES123/.git/objects/83/72f7e8456c384ffafd5dc943efb2bfe492f8ca
/home/jupyter/ES123/.git/objects/83/810fe0a08dea44dd68a19a56f8e0b6b6076eac
/home/jupyter/ES123/.git/objects/83/afc78087a4291fffff894134a9426acaee6171
/home/jupyter/ES123/.git/objects/86/9c3fa363d98c03c8a8c40be583b8c7b332ff02
/home/jupyter/ES123/.git/objects/88/f4c09ec4ab3055ea72b07bf21fb43ac8a8337b
/home/jupyter/ES123/.git/objects/8a/7b81af8aa689dee7e078adce7f1b5eff6ab16c
/home/jupyter/ES123/.git/objects/8a/eb3c608a87227a9ef8c06c80307b0d7d369725
/home/jupyter/ES123/.git/objects/8b/2c8fdfb7573b89dad8b8a3cb2c68c9a822691d
/home/jupyter/ES123/.git/objects/8b/33e4615527e12b3f1e117fee4a19b7912fc474
/home/jupyter/ES123/.git/objects/8b/667576953a9cd06314b3a0218b4692853216e8
/home/jupyter/ES123/.git/objects/8b/aefd486351f0f2970ddcc0657583e6095deef5
/home/jupyter/ES123/.git/objects/8c/08d42dfaea0bbab5b1dc437c200ffdb7c45669
/home/jupyter/ES123/.git/objects/8e/703ac8ad86055c0fe4e26fecaebd60206d8e6d
/home/jupyter/ES123/.git/objects/8f/43fe574c9ae91d7596a8f11936b1a7c6057b8c
/home/jupyter/ES123/.git/objects/91/1ed8624ddfe9546d1496e76c24b0b91f633010
/home/jupyter/ES123/.git/objects/91/22b232d1df2c01a698a5c1e8c7ebd469a0ddef
/home/jupyter/ES123/.git/objects/91/59cbdfd65e1e28305e64775b691c96b8e2f3f5
/home/jupyter/ES123/.git/objects/91/ac70c87af2e75241eb21c9d29336834f879940
/home/jupyter/ES123/.git/objects/92/92d0016659c794c37c92f97df507f966609ebc
/home/jupyter/ES123/.git/objects/93/c866e421dde6b38b7038067736a09ac25382e3
/home/jupyter/ES123/.git/objects/95/4465810c3bda658cbc76122a0ca62a8a713435
/home/jupyter/ES123/.git/objects/95/8974e3f843156385e625ecd98184c38c5fa196
/home/jupyter/ES123/.git/objects/96/9c74ef7bdc90e7daad9d8d51078a359fe5ef3f
/home/jupyter/ES123/.git/objects/96/f5a800f984fc1e59d1c9f3ee15b5ff2cdbc8b1
/home/jupyter/ES123/.git/objects/97/c3688e2ccd3be801be6d3ecd1afddc4d887751
/home/jupyter/ES123/.git/objects/99/87e8d2e6aa23bbe0f862790c93a9bc36de3d97
/home/jupyter/ES123/.git/objects/9b/3e199219223081b4d5f9319986da8e61a7c615
/home/jupyter/ES123/.git/objects/9b/f717b400c171e8553bc8f2037f719e31be9720
/home/jupyter/ES123/.git/objects/9c/1b4dd36eebd9f770a516fa7448ce3f3b846e96
/home/jupyter/ES123/.git/objects/9c/3d6249067436905e9b9da33227550a76b7dd7f
/home/jupyter/ES123/.git/objects/9d/63aa4c3f3f406bcff8db2258959f0b37d0c5a2
/home/jupyter/ES123/.git/objects/9d/b7aca06e8feddb67c8a68fbbca8aba618861d5
/home/jupyter/ES123/.git/objects/9e/12f82a86cf855e0a114bf106c3ea25607646c4
/home/jupyter/ES123/.git/objects/9e/e77f4682b5d190b27a771a9f68b2501b625bfe
/home/jupyter/ES123/.git/objects/a3/4e6c6b05574c83e45c2025b794d64a8d3f4399
/home/jupyter/ES123/.git/objects/a4/0af11c8ca9d62516c6b8636d5c955f4fcbcbe2
/home/jupyter/ES123/.git/objects/a4/8251c2e3fb7dfc1ae14995f8b301edeaab07fe
/home/jupyter/ES123/.git/objects/a7/0ae3b0081c56e6e8a4fef297869e8cd176b545
/home/jupyter/ES123/.git/objects/a9/5281f3ccf473497e0412f16713982608b0a612
/home/jupyter/ES123/.git/objects/aa/44b6ad7eceec5b5de87c4255733ca5f3149cc9
/home/jupyter/ES123/.git/objects/ab/34c3fd5a209b7192e575e71be951ed451ca593
/home/jupyter/ES123/.git/objects/ac/4c7e0e4e97b41c8fa9aeba4bb815e020943a10
/home/jupyter/ES123/.git/objects/ac/96d1a9387659112aab8c1faa887724102bed41
/home/jupyter/ES123/.git/objects/ad/5e9a3a59fb9bd05260c6189a0afdb84e5e0ecd
/home/jupyter/ES123/.git/objects/ae/324ab3cca5a43cf2fd989c6db71e84d0fe05d8
/home/jupyter/ES123/.git/objects/ae/a7a0a04ed934c281bc1266a64cd3782bff4684
/home/jupyter/ES123/.git/objects/af/55eabc7f59bb4f3e45d0ea79f797da905043ff
/home/jupyter/ES123/.git/objects/af/b85a268edfe30e4b1155a57c314f5d2e2671ea
/home/jupyter/ES123/.git/objects/b0/338aeae3e02860e42d26136b8e0b4944712a3b
/home/jupyter/ES123/.git/objects/b1/15d456dbde1cb732846d687f513742dc6b6c9f
/home/jupyter/ES123/.git/objects/b2/566b070d62c802e4766fa6f7424da3b073aab5
/home/jupyter/ES123/.git/objects/b2/585f7dc40f3bad45c3194b72ef427ef9fb2230
/home/jupyter/ES123/.git/objects/b8/4d9eee5232662a350253440dc6c2dcf21c6c2d
/home/jupyter/ES123/.git/objects/b8/77fd6c9e3d79a74a2865a2a184e4144aa3bcfd
/home/jupyter/ES123/.git/objects/b9/10f22a6a35e04f34b4d9e348900c605a0ff79f
/home/jupyter/ES123/.git/objects/b9/19b8c8d2bd1f3a00d92e61ac248af807b45958
/home/jupyter/ES123/.git/objects/b9/1f6e147b0965bd814a50ec44c39d28e896ecde
/home/jupyter/ES123/.git/objects/b9/80bbe26918ccb8f5097c150d22c86860c16759
/home/jupyter/ES123/.git/objects/b9/8d2627af3bf693a1a63b00ef6e30f8b8a501f6
/home/jupyter/ES123/.git/objects/b9/aa1bd79b5b1aa9ef73e94ece831d724381043e
/home/jupyter/ES123/.git/objects/ba/52e94b22de53303e2fcdab54359a87928296c3
/home/jupyter/ES123/.git/objects/ba/815a4e7b6be65c55b3e92cfec3c91e8771fafd
/home/jupyter/ES123/.git/objects/ba/890dbed659797cdd22f24c006e2f96028d17b2
/home/jupyter/ES123/.git/objects/bb/96deee2deb697a48370985751c57d708ecd6c6
/home/jupyter/ES123/.git/objects/bd/367185bdb20f26058d9bfa28750677092e4533
/home/jupyter/ES123/.git/objects/bf/767ca376727920ce99cdf31689615c5adab896
/home/jupyter/ES123/.git/objects/c2/c2684872b5ddb274afea951a721925cd5220f0
/home/jupyter/ES123/.git/objects/c3/381d56aa8cb4b1634ee76b991cb9a1a34784b2
/home/jupyter/ES123/.git/objects/c4/1e22c3c1b12614794aa791f910553afe2dc626
/home/jupyter/ES123/.git/objects/c6/fe6683ecc370bb4b21bce82b3292a50659ac2e
/home/jupyter/ES123/.git/objects/c7/4d2f0c2f13c4d6099b2792ad87e75710f9c76c
/home/jupyter/ES123/.git/objects/c8/55cf37357582af7ddbc90084bb3b9247ec8c81
/home/jupyter/ES123/.git/objects/c8/6975ef1e33a68684447e1c12db540bbd9b144f
/home/jupyter/ES123/.git/objects/ca/577dba84be5f5a23bc8c171893511c4b8f5fdc
/home/jupyter/ES123/.git/objects/ca/83293f493b165daf57d837558cdb3d82f8110a
/home/jupyter/ES123/.git/objects/ca/865c9892ed371754bf0241e6836d237e852597
/home/jupyter/ES123/.git/objects/ca/9240a1e320ffd0ba40e6e4df026ac229f323d6
/home/jupyter/ES123/.git/objects/ca/beeea711c61f97398738305bf18621ec9ffcaf
/home/jupyter/ES123/.git/objects/ca/f7cdafe743fbb85c21746c2f4369d9f20ce14e
/home/jupyter/ES123/.git/objects/cd/2912a992a2134f2ae65fbf0bb37da50b3bdda3
/home/jupyter/ES123/.git/objects/cd/8efdac227f8f13eae7decf1d11664fd027809a
/home/jupyter/ES123/.git/objects/ce/ff04b68023e2f3521583709995604cd03f96f6
/home/jupyter/ES123/.git/objects/cf/623f6c3857c2384c21887b4f5a59b6788c7b8d
/home/jupyter/ES123/.git/objects/cf/b8c5c8743b72496f5a7d9c85e51259ac0fd199
/home/jupyter/ES123/.git/objects/d0/e2687a1de58eb5bcc50c4be4b3f44334b9647b
/home/jupyter/ES123/.git/objects/d3/2ce9888111486a0d7ffe128eb97cb14cbf19fd
/home/jupyter/ES123/.git/objects/d3/f900cd01ea0c1092906a15b3c264897671b3a0
/home/jupyter/ES123/.git/objects/d4/89b73023cf9cd113800fb5baa2f43193556824
/home/jupyter/ES123/.git/objects/d5/04cd06c8ee07406d07c99998300b828409bfa7
/home/jupyter/ES123/.git/objects/d7/ff48b180e1bc340ef6005fa61cc5735e4dbb7f
/home/jupyter/ES123/.git/objects/d8/7194b1b15f124633fef87342f154076ab6f991
/home/jupyter/ES123/.git/objects/da/4618659b124b8b8f7fbdc6d35d1afe3d4c5f05
/home/jupyter/ES123/.git/objects/da/8f3b5da3172465837015a1bc0939b2fdaacd1a
/home/jupyter/ES123/.git/objects/da/c416f167618bed9976c4b48225a042f31bd131
/home/jupyter/ES123/.git/objects/db/b5239532a07ce758fa5494ec1363ff7bd69806
/home/jupyter/ES123/.git/objects/db/ef5b975ef1291d90a2389d6215d429d519f147
/home/jupyter/ES123/.git/objects/dc/b05e45f430a329b8eea63324017b7765e993f3
/home/jupyter/ES123/.git/objects/dc/ed0646a608cd554eac33f53093fdeb6ea04b3b
/home/jupyter/ES123/.git/objects/dd/12582d5923615b1b1ad609cd5b80deb1b0eb0d
/home/jupyter/ES123/.git/objects/de/02c762daf9789b690be16acd00d13e4066d74b
/home/jupyter/ES123/.git/objects/de/6e373f91995b05ab25b8947b7de1482cab5bca
/home/jupyter/ES123/.git/objects/df/66d2d654fa37e72ef1feaf811a3a71e27be451
/home/jupyter/ES123/.git/objects/df/f827047f4ba81e53e1657d4de1f7d27001a970
/home/jupyter/ES123/.git/objects/e2/ac8bfc91befdcdbdcd2eb123ef8c0b2f92820c
/home/jupyter/ES123/.git/objects/e2/c208302c0e12954430fcda7f79cb15f0b317ef
/home/jupyter/ES123/.git/objects/e2/d4ccb13275e2708e35bceea49189b752c11e6f
/home/jupyter/ES123/.git/objects/e4/c4bc196b21e7de1a36e32cb8292b27958330b7
/home/jupyter/ES123/.git/objects/e7/4902cceaba393fd130495b7c0839f228c1dc4f
/home/jupyter/ES123/.git/objects/e7/c0eb0463c46f711376275f527581e6f0af3d6e
/home/jupyter/ES123/.git/objects/ec/928a07069e413d2c5c34697ce9980a22b54108
/home/jupyter/ES123/.git/objects/f0/f6c5c137eaa96981b1d8ef291c43b89606e951
/home/jupyter/ES123/.git/objects/f2/79fcdca81cac627ec665cb3c10424a2cc616eb
/home/jupyter/ES123/.git/objects/f5/b6f8bed61e608260a7810296640c6468d707eb
/home/jupyter/ES123/.git/objects/f6/056e8eafa2d10b15bf2a92f44a3de43b931df3
/home/jupyter/ES123/.git/objects/f8/9cb5e6088807d96a5e5e2e9d24d751a2f81683
/home/jupyter/ES123/.git/objects/f8/a707c21b7bee545cd9b08b209b799bd5d8d924
/home/jupyter/ES123/.git/objects/fd/f111b3b43af723702a8b8c7e02b602c3637e68
/home/jupyter/ES123/.git/objects/pack/pack-9ec1eaff1f454b48fbeb420ba2a1632aa38ab51c.idx
/home/jupyter/ES123/.git/objects/pack/pack-9ec1eaff1f454b48fbeb420ba2a1632aa38ab51c.pack
/home/jupyter/ES123/.git/ORIG_HEAD
/home/jupyter/ES123/.git/packed-refs
/home/jupyter/ES123/.git/refs/heads/master
/home/jupyter/ES123/.git/refs/remotes/origin/HEAD
/home/jupyter/ES123/.git/refs/remotes/origin/master
/home/jupyter/ES123/.gitignore
/home/jupyter/ES123/Lectures/.ipynb_checkpoints/Lecture 0. Introduction-checkpoint.ipynb
/home/jupyter/ES123/Lectures/.ipynb_checkpoints/Lecture 10. Strings-checkpoint.ipynb
/home/jupyter/ES123/Lectures/.ipynb_checkpoints/Lecture 11. Arrays-checkpoint.ipynb
/home/jupyter/ES123/Lectures/.ipynb_checkpoints/Lecture 12. Dictionaries-checkpoint.ipynb
/home/jupyter/ES123/Lectures/.ipynb_checkpoints/Lecture 13. Tuples-checkpoint.ipynb
/home/jupyter/ES123/Lectures/.ipynb_checkpoints/Lecture 14. Data structure selection-checkpoint.ipynb
/home/jupyter/ES123/Lectures/.ipynb_checkpoints/Lecture 15. Files-checkpoint.ipynb
/home/jupyter/ES123/Lectures/.ipynb_checkpoints/Lecture 16. Types and Objects-checkpoint.ipynb
/home/jupyter/ES123/Lectures/.ipynb_checkpoints/Lecture 17. Types and Functions-checkpoint.ipynb
/home/jupyter/ES123/Lectures/.ipynb_checkpoints/Lecture 18. Methods-checkpoint.ipynb
/home/jupyter/ES123/Lectures/.ipynb_checkpoints/Lecture 19. Abstract types-checkpoint.ipynb
/home/jupyter/ES123/Lectures/.ipynb_checkpoints/Lecture 1. Software-Hardware Interface-checkpoint.ipynb
/home/jupyter/ES123/Lectures/.ipynb_checkpoints/Lecture 2. Computer Representation of Data-checkpoint.ipynb
/home/jupyter/ES123/Lectures/.ipynb_checkpoints/Lecture 3. The Way of the Program-checkpoint.ipynb
/home/jupyter/ES123/Lectures/.ipynb_checkpoints/Lecture 4. Problem Solving-checkpoint.ipynb
/home/jupyter/ES123/Lectures/.ipynb_checkpoints/Lecture 5. Variables, Expressions and Statements-checkpoint.ipynb
/home/jupyter/ES123/Lectures/.ipynb_checkpoints/Lecture 6. Functions-checkpoint.ipynb
/home/jupyter/ES123/Lectures/.ipynb_checkpoints/Lecture 7. Conditionals and Recursion-checkpoint.ipynb
/home/jupyter/ES123/Lectures/.ipynb_checkpoints/Lecture 8. Fruitful Functions-checkpoint.ipynb
/home/jupyter/ES123/Lectures/.ipynb_checkpoints/Lecture 9. Iteration-checkpoint.ipynb
/home/jupyter/ES123/Lectures/.ipynb_checkpoints/wc-checkpoint.jl
/home/jupyter/ES123/Lectures/Lecture 0. Introduction.ipynb
/home/jupyter/ES123/Lectures/Lecture 10. Strings.ipynb
/home/jupyter/ES123/Lectures/Lecture 11. Arrays.ipynb
/home/jupyter/ES123/Lectures/Lecture 12. Dictionaries.ipynb
/home/jupyter/ES123/Lectures/Lecture 13. Tuples.ipynb
/home/jupyter/ES123/Lectures/Lecture 14. Data structure selection.ipynb
/home/jupyter/ES123/Lectures/Lecture 15. Files.ipynb
/home/jupyter/ES123/Lectures/Lecture 16. Types and Objects.ipynb
/home/jupyter/ES123/Lectures/Lecture 17. Types and Functions.ipynb
/home/jupyter/ES123/Lectures/Lecture 18. Methods.ipynb
/home/jupyter/ES123/Lectures/Lecture 19. Abstract types.ipynb
/home/jupyter/ES123/Lectures/Lecture 1. Software-Hardware Interface.ipynb
/home/jupyter/ES123/Lectures/Lecture 2. Computer Representation of Data.ipynb
/home/jupyter/ES123/Lectures/Lecture 3. The Way of the Program.ipynb
/home/jupyter/ES123/Lectures/Lecture 4. Problem Solving.ipynb
/home/jupyter/ES123/Lectures/Lecture 5. Variables, Expressions and Statements.ipynb
/home/jupyter/ES123/Lectures/Lecture 6. Functions.ipynb
/home/jupyter/ES123/Lectures/Lecture 7. Conditionals and Recursion.ipynb
/home/jupyter/ES123/Lectures/Lecture 8. Fruitful Functions.ipynb
/home/jupyter/ES123/Lectures/Lecture 9. Iteration.ipynb
/home/jupyter/ES123/Lectures/output.txt
/home/jupyter/ES123/Lectures/wc.jl
/home/jupyter/ES123/LICENSE
/home/jupyter/ES123/README.md

joinpath takes a directory and a file name and joins them into a complete path.

Julia provides a function called walkdir that is similar to this one but more versatile.

Catching exceptions

A lot of things can go wrong when you try to read and write files. If you try to open a file that doesn’t exist, you get a SystemError:


In [12]:
fin = open("bad_file.txt")


SystemError: opening file bad_file.txt: No such file or directory

Stacktrace:
 [1] #systemerror#44 at ./error.jl:64 [inlined]
 [2] systemerror(::String, ::Bool) at ./error.jl:64
 [3] open(::String, ::Bool, ::Bool, ::Bool, ::Bool, ::Bool) at ./iostream.jl:104
 [4] open(::String) at ./iostream.jl:113
 [5] include_string(::String, ::String) at ./loading.jl:522

If you don’t have permission to access a file:


In [13]:
fout = open("/etc/passwd", "w")


SystemError: opening file /etc/passwd: Permission denied

Stacktrace:
 [1] #systemerror#44 at ./error.jl:64 [inlined]
 [2] systemerror(::String, ::Bool) at ./error.jl:64
 [3] open(::String, ::Bool, ::Bool, ::Bool, ::Bool, ::Bool) at ./iostream.jl:104
 [4] open(::String, ::String) at ./iostream.jl:132
 [5] include_string(::String, ::String) at ./loading.jl:522

To avoid these errors, you could use functions like ispath and isfile, but it would take a lot of time and code to check all the possibilitie.

It is better to go ahead and try—and deal with problems if they happen—which is exactly what the try statement does. The syntax is similar to an if statement:


In [14]:
try    
    fin = open("bad_file.txt")
catch exc
    println("Something went wrong: $exc")
end


Something went wrong: SystemError("opening file bad_file.txt", 2, nothing)

Julia starts by executing the try clause. If all goes well, it skips the catch clause and proceeds. If an exception occurs, it jumps out of the try clause and runs the catch clause.

Handling an exception with a try statement is called catching an exception. In this example, the except clause prints an error message that is not very helpful. In general, catching an exception gives you a chance to fix the problem, or try again, or at least end the program gracefully.

In code that performs state changes or uses resources like files, there is typically clean-up work (such as closing files) that needs to be done when the code is finished. Exceptions potentially complicate this task, since they can cause a block of code to exit before reaching its normal end. The finally keyword provides a way to run some code when a given block of code exits, regardless of how it exits:


In [15]:
f = open("output.txt")
try
    line = readline(f)
    println(line)
finally
    close(f)
end


The best promotion is 150!

JLD

JLD is a widely-used format for data storage with the Julia programming language.

First we have to install the package:


In [16]:
Pkg.add("JLD")


INFO: Package JLD is already installed
INFO: METADATA is out-of-date — you may not have the latest version of JLD
INFO: Use `Pkg.update()` to get the latest versions of your packages

To use the JLD module, begin your code with


In [17]:
using JLD

If you just want to save a few variables and don't care to use the more advanced features, then a simple syntax is:


In [18]:
t = 15
z = [1,3]
save("/tmp/myfile.jld", "t", t, "arr", z)

Here we're explicitly saving t and z as "t" and "arr" within "myfile.jld". You can alternatively pass save a dictionary; the keys must be strings and are saved as the variable names of their values within the JLD file.

You can read these variables back in with:


In [19]:
d = load("/tmp/myfile.jld")


Out[19]:
Dict{String,Any} with 2 entries:
  "arr" => [1, 3]
  "t"   => 15

which reads the entire file into a returned dictionary d. Or you can be more specific and just request particular variables of interest. For example,

z = load("/tmp/myfile.jld", "arr")

will return the value of "arr" from the file and assign it back to z.

Pipes

Most operating systems provide a command-line interface, also known as a shell. Shells usually provide commands to navigate the file system and launch applications. For example, in Unix you can change directories with cd, display the contents of a directory with ls, and launch a web browser by typing (for example) firefox.

Any program that you can launch from the shell can also be launched from Julia using a Cmd object, which represents the command:


In [20]:
cmd = `echo hello`


Out[20]:
`echo hello`

The function run executes the command:


In [21]:
run(cmd)


hello

The hello is the output of the echo command, sent to STDOUT. The run method itself returns nothing, and throws an ErrorException if the external command fails to run successfully.

If you want to read the output of the external command, readstring can be used instead:


In [22]:
a = readstring(`echo hello`)


Out[22]:
"hello\n"

For example, most Unix systems provide a command called md5sum that reads the contents of a file and computes a “checksum”. You can read about MD5 at http://en.wikipedia.org/wiki/Md5. This command provides an efficient way to check whether two files have the same contents. The probability that different contents yield the same checksum is very small (that is, unlikely to happen before the universe collapses).

You can use a pipe to run md5sum from Julia and get the result:


In [23]:
filename = "output.txt"
cmd = `md5sum $filename`
md5 = readstring(cmd)


Out[23]:
"182b63c001d0ebb714f03f5f1a9a99f3  output.txt\n"

Modules

Any file that contains Julia code can be imported as a module. For example, suppose you have a file named "wc.jl" with the following code:

function linecount(filename)
    count = 0
    for line in readline(filename)
        count += 1
    end
    count
end

print(linecount("wc.jl"))

If you run this program, it reads itself and prints the number of lines in the file, which is 9. You can also include it like this:


In [24]:
include("wc.jl")


9

Modules in Julia are separate variable workspaces, i.e. they introduce a new global scope. They are delimited syntactically, inside module ... end. Modules allow you to create top-level definitions without worrying about name conflicts when your code is used together with somebody else's. Within a module, you can control which names from other modules are visible (via importing), and specify which of your names are intended to be public (via exporting).


In [1]:
module LineCount
    export linecount

    function linecount(filename)
        count = 0
        for line in eachline(filename)
            count += 1
        end
        count
    end
end


Out[1]:
LineCount

To call the function linecount we have 2 possibilites:


In [2]:
LineCount.linecount("wc.jl")


Out[2]:
9

In [3]:
using LineCount
linecount("wc.jl")


Out[3]:
9

Files and file names are mostly unrelated to modules; modules are associated only with module expressions. One can have multiple files per module (include inside a module).

Warning: If you try using a module that has already been used, Julia does nothing. It does not re-read the file, even if it has changed.

If you want to reload a module, you can use the built-in function reload, but it can be tricky, so the safest thing to do is restart the kernel and then using the module again.

Debugging

When you are reading and writing files, you might run into problems with whitespace. These errors can be hard to debug because spaces, tabs and newlines are normally invisible:


In [4]:
s = "1 2\t 3\n 4"
println(s)


1 2	 3
 4

The built-in function repr can help. It takes any object as an argument and returns a string representation of the object.


In [5]:
repr(s)


Out[5]:
"\"1 2\\t 3\\n 4\""

This can be helpful for debugging.

One other problem you might run into is that different systems use different characters to indicate the end of a line. Some systems use a newline, represented \n. Others use a return character, represented \r. Some use both. If you move files between different systems, these inconsistencies can cause problems.