在 Linux 系统中,可以通过多种方式判断文件是否存在。以下是常用的方法:
test
命令或 [ ]
:if [ -f "/path/to/file" ]; then
echo "文件存在"
else
echo "文件不存在"
fi
-f
:判断是否为普通文件(非目录、设备文件等)。-e
:判断文件是否存在(包括目录、设备文件等)。[[ ]]
(推荐,兼容性更强):if [[ -f "/path/to/file" ]]; then
echo "文件存在"
fi
access()
函数:#include <unistd.h>
#include <stdio.h>
int main() {
if (access("/path/to/file", F_OK) == 0) {
printf("文件存在\n");
} else {
printf("文件不存在\n");
}
return 0;
}
F_OK
:检查文件是否存在。R_OK
(可读)、W_OK
(可写)、X_OK
(可执行)。stat()
函数(获取文件详细信息):#include <sys/stat.h>
#include <stdio.h>
int main() {
struct stat buffer;
if (stat("/path/to/file", &buffer) == 0) {
printf("文件存在\n");
} else {
printf("文件不存在\n");
}
return 0;
}
os.path
:import os
if os.path.isfile("/path/to/file"):
print("文件存在")
os.path.exists()
:文件或目录存在均返回 True
。os.path.isfile()
:仅对普通文件返回 True
。pathlib
(Python 3.4+):from pathlib import Path
if Path("/path/to/file").is_file():
print("文件存在")
File.exists()
file_exists()
-e $filename
-f
和 stat()
会解析符号链接指向的实际文件。根据你的使用场景选择合适的方案即可!