在 Python 中,你可以使用 `os` 模块来判断一个文件是否存在。以下是使用 `os` 模块的示例代码:
import osdef check_file_exists(file_path):if os.path.exists(file_path):print(f"{file_path} 存在")获取文件的绝对路径abs_path = os.path.abspath(file_path)print(f"绝对路径: {abs_path}")获取文件大小file_size = os.path.getsize(file_path)print(f"文件大小: {file_size} 字节")else:print(f"{file_path} 不存在")替换为你的文件路径check_file_exists("example.txt")
如果你使用的是 Python 3.4 或更高版本,你还可以使用 `pathlib` 模块,它提供了更直观和面向对象的文件系统路径操作方式。以下是使用 `pathlib` 模块的示例代码:

from pathlib import Pathdef check_file_exists(file_path):p = Path(file_path)if p.exists():print(f"{file_path} 存在")获取文件的绝对路径abs_path = p.resolve()print(f"绝对路径: {abs_path}")获取文件大小file_size = p.stat().st_sizeprint(f"文件大小: {file_size} 字节")else:print(f"{file_path} 不存在")替换为你的文件路径check_file_exists("example.txt")
在这两个示例中,我们首先检查文件是否存在,然后获取文件的绝对路径和大小。请确保将 `"example.txt"` 替换为你想要检查的文件的实际路径
