Is there a built-in function to get the size of a folder?

I saw that there are stat and filesize, but I don’t see a recursive option.

Is there a small package or another function that can give me the cumulative size of all files in a folder?

Another thing I am not sure about is if stat works on windows?

I tried the code below and I think it works now.

using Logging
function totalsize(dirpath)
	total = 0
	for (root,dir,files) in walkdir(dirpath)
		total += filesize(root)
		@info filesize(root) root
		for f in files
			file = joinpath(root,f)
			size = filesize(file)
			total += size
			@info size file
		end
		print(" "^80,"\r")
		print(total," B","\r")
	end
end
1 Like
julia> 0.668766975402832 * 1024^2
701253.0
1 Like

Yeah that was a stupid mistake. Thanks

Here is a version that is less noisy.
Is it bad practice to add methods to Base?

function Base.filesize(dirpath::String, recursive::Bool)
	if !recursive
		return filesize(dirpath)
	else
		total = 0
		for (root,dirs,files) in walkdir(dirpath)
			total += filesize(root)
			for f in files
				file = joinpath(root,f)
				size = filesize(file)
				total += size
			end
		end
		return total
	end
end

Example:

julia> map((x)->basename(x)=>filesize(x,true),
           readdir(joinpath(homedir(), ".julia"), join=true))
14-element Vector{Pair{String, Int64}}:
       "artifacts" => 2647756716
          "clones" => 4096
        "compiled" => 641285002
           "conda" => 9595941797
             "dev" => 3157598
    "environments" => 270825
            "logs" => 711615
    "makiegallery" => 8444804
           "noise" => 4434
        "packages" => 81462643
 "pluto_notebooks" => 17462
           "prefs" => 4113
      "registries" => 283915844
   "scratchspaces" => 37441
3 Likes

But what if there are many levels of folders in each folder?

In this case, this method definition is a type piracy.
According to official documentation:

“Type piracy” refers to the practice of extending or redefining methods in Base or other packages on types that you have not defined.

link: Style Guide · The Julia Language

And yes, type piracy is considered bad practice.

2 Likes

The code should work in that case.
walkdir walks through the full substructure of the folder.