lars
lars

Reputation: 1986

How to read a Bunch of files in a directory in lua

I have a path (as a string) to a directory. In that directory, are a bunch of text files. I want to go to that directory open it, and go to each text file and read the data.

I've tried

f = io.open(path)
f:read("*a")

I get the error "nil Is a directory"

I've tried:

f = io.popen(path)

I get the error: "Permission denied"

Is it just me, but it seems to be a lot harder than it should be to do basic file io in lua?

Upvotes: 3

Views: 6032

Answers (2)

Roberto Ierusalimschy
Roberto Ierusalimschy

Reputation: 478

You can also use the following script to list the names of the files in a given directory (assuming Unix/Posix):

dirname = '.'
f = io.popen('ls ' .. dirname)
for name in f:lines() do print(name) end

Upvotes: 4

Etan Reisner
Etan Reisner

Reputation: 80921

A directory isn't a file. You can't just open it.

And yes, lua itself has (intentionally) limited functionality.

You can use luafilesystem or luaposix and similar modules to get more features in this area.

Upvotes: 4

Related Questions