判断路径是否存在适合在写入、读取或执行命令前做前置检查。
判断文件是否存在
Python 示例:
exists = sandbox.files.exists("/tmp/result.json")
if not exists:
sandbox.files.write("/tmp/result.json", "{}")TypeScript 示例:
const exists = await sandbox.files.exists("/tmp/result.json");
if (!exists) {
await sandbox.files.write("/tmp/result.json", "{}");
}获取路径信息
Python 示例:
info = sandbox.files.get_info("/tmp/result.json")
print(info.name)
print(info.type)
print(info.path)TypeScript 示例:
const info = await sandbox.files.getInfo("/tmp/result.json");
console.log(info.name);
console.log(info.type);
console.log(info.path);使用建议
exists() 只能说明检查时刻路径存在。并发任务可能在检查后修改文件,因此关键写入仍需要业务侧做好幂等和错误处理。
该文章对您有帮助吗?