如何在Lua中将文件输出到特定文件夹?

如果我有一个文本字符串 "Testing",并且我在工作目录 C:/home/files/ 中,如何输出到目录 C:/home/files2/

我的当前代码为:

file = io.open("test.lua", "w", "C:/home/files2/")
file:write("Testing")
file:close()

我该如何使这个工作?

点赞
用户6004556
用户6004556

原文:

It turns out you cannot output a file to a specific directory.

Well in **normal lua!** there are external libraries you can use.

Simply install Lua File System following these instruction:

[Instructions](https://keplerproject.github.io/luafilesystem/manual.html#introduction "Instructions")

Then do this:

local lfs = require( "lfs" ) print(lfs.currentdir()) lfs.chdir("C:/home/files2/") print(lfs.currentdir())

file = io.open("test.lua", "w") file:write("Testing") file:close()


翻译:

事实证明,您无法将文件输出到特定目录。

嗯,在普通的lua中,有一些外部库可以使用。

按照以下说明安装Lua文件系统:

说明

然后,执行以下操作:

local lfs = require("lfs")
print(lfs.currentdir())
lfs.chdir("C:/home/files2/")
print(lfs.currentdir())

file = io.open("test.lua", "w")
file:write("Testing")
file:close()

```

2017-03-13 08:55:31
用户4687565
用户4687565

Lua支持标准的路径规范。

如果您想要文件在工作目录的子目录中,您可以在文件名前加上文件夹名称:

f=io.open('folder/file','w');

您可以使用双点序列来指定相对路径中的上一级目录:

f=io.open('../files2','w')

至少在Linux上,您可以使用绝对路径:

f=io.open('/home/username/folder/folder/file,'w')

与许多命令行应用程序一样,在创建文件之前必须存在文件夹。

您可以通过检查f值来快速验证文件打开是否成功:

print(f)
--output
file (0xb4acf0)
2017-03-13 11:26:14