program tip

Lua에 파일이 있는지 확인

radiobox 2020. 11. 24. 07:51
반응형

Lua에 파일이 있는지 확인


Lua를 사용하여 파일이 있는지 어떻게 확인할 수 있습니까?


시험

function file_exists(name)
   local f=io.open(name,"r")
   if f~=nil then io.close(f) return true else return false end
end

그러나이 코드는 파일을 읽기 위해 열 수 있는지 여부 만 테스트합니다.


일반 Lua를 사용하면 LHF에 따라 파일을 읽기 위해 열 수 있는지 확인하는 것이 가장 좋습니다. 이것은 거의 항상 충분합니다. 그러나 더 많은 것을 원한다면 Lua POSIX 라이브러리를 로드하고 posix.stat(경로) 가 non-를 반환 하는지 확인하십시오 nil.


여기 에서 인용 하겠습니다

나는 이것을 사용하지만 실제로 오류를 확인합니다.

require("lfs")
-- no function checks for errors.
-- you should check for them

function isFile(name)
    if type(name)~="string" then return false end
    if not isDir(name) then
        return os.rename(name,name) and true or false
        -- note that the short evaluation is to
        -- return false instead of a possible nil
    end
    return false
end

function isFileOrDir(name)
    if type(name)~="string" then return false end
    return os.rename(name, name) and true or false
end

function isDir(name)
    if type(name)~="string" then return false end
    local cd = lfs.currentdir()
    local is = lfs.chdir(name) and true or false
    lfs.chdir(cd)
    return is
end

os.rename (name1, name2)는 name1의 이름을 name2로 바꿉니다. 동일한 이름을 사용하고 아무것도 변경해서는 안됩니다 (악성 오류가있는 경우 제외). 모든 것이 잘 작동하면 true를 반환하고 그렇지 않으면 nil과 오류 메시지를 반환합니다. lfs를 사용하지 않으려면 파일을 열지 않고 파일과 디렉토리를 구분할 수 없습니다 (약간 느리지 만 괜찮습니다).

그래서 LuaFileSystem없이

-- no require("lfs")

function exists(name)
    if type(name)~="string" then return false end
    return os.rename(name,name) and true or false
end

function isFile(name)
    if type(name)~="string" then return false end
    if not exists(name) then return false end
    local f = io.open(name)
    if f then
        f:close()
        return true
    end
    return false
end

function isDir(name)
    return (exists(name) and not isFile(name))
end

짧아 보이지만 시간이 오래 걸립니다 ... 파일을 여는 것도 위험합니다

즐겁게 코딩하세요!


Premake 및 LUA 버전 5.3.4를 사용하는 경우 :

if os.isfile(path) then
    ...
end

완전성을 위해 :를 사용하여 운을 시험해 볼 수도 있습니다 path.exists(filename). 어떤 Lua 배포판에 실제로이 path네임 스페이스 ( update : Penlight ) 가 있는지 확실하지 않지만 적어도 Torch에 포함되어 있습니다.

$ th

  ______             __   |  Torch7
 /_  __/__  ________/ /   |  Scientific computing for Lua.
  / / / _ \/ __/ __/ _ \  |  Type ? for help
 /_/  \___/_/  \__/_//_/  |  https://github.com/torch
                          |  http://torch.ch

th> path.exists(".gitignore")
.gitignore  

th> path.exists("non-existing")
false   

debug.getinfo(path.exists) tells me that its source is in torch/install/share/lua/5.1/pl/path.lua and it is implemented as follows:

--- does a path exist?.
-- @string P A file path
-- @return the file path if it exists, nil otherwise
function path.exists(P)
    assert_string(1,P)
    return attrib(P,'mode') ~= nil and P
end

If you are willing to use lfs, you can use lfs.attributes. It will return nil in case of error:

require "lfs"

if lfs.attributes("non-existing-file") then
    print("File exists")
else
    print("Could not get attributes")
end

Although it can return nil for other errors other than a non-existing file, if it doesn't return nil, the file certainly exists.


An answer which is windows only checks for files and folders, and also requires no additional packages. It returns true or false.

io.popen("if exist "..PathToFileOrFolder.." (echo 1)"):read'*l'=='1'

io.popen(...):read'*l' - executes a command in the command prompt and reads the result from the CMD stdout

if exist - CMD command to check if an object exists

(echo 1) - prints 1 to stdout of the command prompt


You can also use the 'paths' package. Here's the link to the package

Then in Lua do:

require 'paths'

if paths.filep('your_desired_file_path') then
    print 'it exists'
else
    print 'it does not exist'
end

Not necessarily the most ideal as I do not know your specific purpose for this or if you have a desired implementation in mind, but you can simply open the file to check for its existence.

local function file_exists(filename)
    local file = io.open(filename, "r")
    if (file) then
        -- Obviously close the file if it did successfully open.
        file:close()
        return true
    end
    return false
end

io.open returns nil if it fails to open the file. As a side note, this is why it is often used with assert to produce a helpful error message if it is unable to open the given file. For instance:

local file = assert(io.open("hello.txt"))

If the file hello.txt does not exist, you should get an error similar to stdin:1: hello.txt: No such file or directory.


Lua 5.1:

function file_exists(name)
   local f = io.open(name, "r")
   return f ~= nil and io.close(f)
end

For library solution, you can use either paths or path.

From the official document of paths:

paths.filep(path)

Return a boolean indicating whether path refers to an existing file.

paths.dirp(path)

Return a boolean indicating whether path refers to an existing directory.

Although the names are a little bit strange, you can certainly use paths.filep() to check whether a path exists and it is a file. Use paths.dirp() to check whether it exists and it is a directory. Very convenient.

If you prefer path rather than paths, you can use path.exists() with assert() to check the existence of a path, getting its value at the same time. Useful when you are building up path from pieces.

prefix = 'some dir'

filename = assert(path.exist(path.join(prefix, 'data.csv')), 'data.csv does not exist!')

If you just want to check the boolean result, use path.isdir() and path.isfile(). Their purposes are well-understood from their names.


How about doing something like this?

function exist(file)
  local isExist = io.popen(
    '[[ -e '.. tostring(file) ..' ]] && { echo "true"; }')
  local isIt = isExist:read("*a")
  isExist:close()
  isIt = string.gsub(isIt, '^%s*(.-)%s*$', '%1')
  if isIt == "true" then
    return true
  end
end

if exist("myfile") then
  print("hi, file exists")
else
  print("bye, file does not exist")
end

IsFile = function(path)
print(io.open(path or '','r')~=nil and 'File exists' or 'No file exists on this path: '..(path=='' and 'empty path entered!' or (path or 'arg "path" wasn\'t define to function call!')))
end

IsFile()
IsFile('')
IsFIle('C:/Users/testuser/testfile.txt')

Looks good for testing your way. :)

참고URL : https://stackoverflow.com/questions/4990990/check-if-a-file-exists-with-lua

반응형