移动文件或目录 (file.move)
声明
操作成败, 错误信息 = file.move(源路径, 目标路径 [, 模式])
参数
- 源路径
文本型,源文件或目录的绝对路径 - 目标路径
文本型,移动后的文件或目录的完整绝对路径,包含目标文件名或目录名 - 模式 20250914+
文本型,可选参数,移动模式。取值:- 空字符串或省略:默认模式(no-clobber),当目标已存在时返回失败
- "overwrite" 或 "o":覆盖模式,直接替换已存在的目标(已存在的目标会被删除)
- "merge" 或 "m":合并模式(仅用于目录),保留目标中已存在的文件
- "overwrite-merge" 或 "om"/"mo":覆盖合并模式,合并目录但覆盖同名文件
返回值
- 操作成败
布尔型,操作成功返回 true,操作失败返回 false - 错误信息
文本型,操作失败时的错误信息
说明
将
源路径指向的文件或目录移动为目标路径;在同一目录下更名即为重命名
该函数是“移动为”语义,不是“移动进”语义。目标路径指定最终的文件或目录,不会自动追加源文件名或目录名;即使目标已存在且为目录,或者目标路径以/结尾,也不会将源文件或目录放入该目录中
例如,要把/a/b/c移动到/d/e/中并保留名称c,目标路径应写为/d/e/c,不能只写/d/e/
目标已存在时,按模式参数处理:默认模式返回失败,覆盖模式替换目标本身,目录合并模式则将源目录内容合并到目标目录
关键词:重命名文件、重命名目录、重命名文件夹、移动文件、移动目录、移动文件夹
该函数在 20250313 以后的版本方可使用
示例
ok, err = file.move(XXT_SCRIPTS_PATH..'/1.zip', XXT_SCRIPTS_PATH..'/2.zip')
if not ok then
sys.alert('移动失败:'..err)
end
注:上述代码中使用了非本章函数 sys.alert
移动到另一个目录并保留名称
-- 假设 /d/e 是已存在的目录,/d/e/c 尚不存在
file.move('/a/b/c', '/d/e/c') -- 正确:将 c 移动为 /d/e/c
-- 以下为独立的错误写法示例,目标是 e 本身,不是 e 目录中的 c
-- file.move('/a/b/c', '/d/e/') -- 默认模式下因目标已存在而失败
-- 覆盖模式会替换 e 本身,不会生成 /d/e/c(20250914+)
-- file.move('/a/b/c', '/d/e/', 'overwrite')
封装“移动进目录”函数
以下为自定义封装示例,需要 20250914 以后的版本。目标目录须已存在,函数会保留源文件或目录名,并将可选的 mode 参数传给 file.move。发生同名冲突时,仍按指定模式处理。
local function file_move_into(src_path, dst_dir, mode)
if file.exists(dst_dir) ~= "directory" then
return false, "Target is not a directory"
end
local name, err = file.path.last_component(src_path)
if not name then
return false, err
end
-- 避免将目标目录本身或其父目录作为最终目标。
if name == "" or name == "/" or name == "." or name == ".." then
return false, "Source path must end with a file or directory name"
end
local dst_path, path_err = file.path.add_component(dst_dir, name)
if not dst_path then
return false, path_err
end
return file.move(src_path, dst_path, mode)
end
-- 假设 /d/e 是已存在的目录,将 c 移动为 /d/e/c
local ok, err = file_move_into("/a/b/c", "/d/e/")
if not ok then
print("移动失败:"..err)
end
-- 如需替换 /d/e/c,可在调用时指定覆盖模式:
-- file_move_into("/a/b/c", "/d/e/", "overwrite")
注:上述代码使用了 file.exists、file.path.last_component 和 file.path.add_component。