Working out which directory the current code was loaded from?

29 views
Skip to first unread message

Peter W A Wood

unread,
Jul 27, 2020, 9:38:20 PM7/27/20
to racket...@googlegroups.com
I have a short racket program/script that reads a file from the directory in which it is stored. The directory structure is something like this:

a/
b/
c/
my-racket.rkt
my-data-file.txt

I want to be able to run the program from the command line no matter what is the current working directory. E.G.:

a> racket b/c/my-racket.rkt
a/b> racket c/my-racket.rkt
a/b/c> racket my-racket.rkt

In order to do so, I need to provide the correct path to my-data-file.txt depending on from where the script was launched. I haven’t learnt about Racket modules yet so I resorted to searching Stack Overflow. I found a code snippet that I used which worked:

(define script-dir (path-only (resolved-module-path-name
(variable-reference->resolved-module-path
(#%variable-reference)))))

Is this the best way to ascertain the directory of the “current module”?

Thanks in advance

Peter


Philip McGrath

unread,
Jul 27, 2020, 9:40:50 PM7/27/20
to Peter W A Wood, Racket Users
For this particular purpose, you want `define-runtime-path`: https://docs.racket-lang.org/reference/Filesystem.html#%28part._runtime-path%29

-Philip


--
You received this message because you are subscribed to the Google Groups "Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to racket-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/racket-users/92DACE01-60C8-445A-A07E-A4E6A6F5F684%40gmail.com.

Peter W A Wood

unread,
Jul 27, 2020, 11:05:05 PM7/27/20
to Racket Users
Many thanks Philip

The resulting code is much neater and, to me, more readable:

(define-runtime-path foo.txt "foo.txt")
(define-runtime-path bar.txt "bar.txt")
(define-runtime-path outfile.txt "outfile.txt")
(define-runtime-path Data/portfolio.csv "../../Data/portfolio.csv")
(define-runtime-path Data/portfolio.csv.gz "../../Data/portfolio.csv.gz”)

Peter
Reply all
Reply to author
Forward
0 new messages