"使用 Python 的 os.path.isfile() 函数判断传入路径是否为文件。\n\n该函数接收一个路径作为参数,返回一个布尔值,表示该路径是否是一个文件。\n\npython\nimport os\n\ndef is_file(path):\n return os.path.isfile(path)\n\n# 示例\nprint(is_file('/path/to/file.txt')) # True\nprint(is_file('/path/to/directory')) # False\n\n\n用法:\n\n1. 导入 os 模块:import os\n2. 使用 os.path.isfile(path) 函数判断路径是否为文件,其中 path 为要判断的路径。\n3. 函数返回 True 表示路径为文件,返回 False 表示路径不是文件。\n\n示例:\n\npython\nimport os\n\ndef is_file(path):\n return os.path.isfile(path)\n\n# 判断文件路径\nfile_path = '/path/to/file.txt'\nif is_file(file_path):\n print(f'"{file_path}" 是一个文件。')\nelse:\n print(f'"{file_path}" 不是一个文件。')\n\n# 判断目录路径\ndirectory_path = '/path/to/directory'\nif is_file(directory_path):\n print(f'"{directory_path}" 是一个文件。')\nelse:\n print(f'"{directory_path}" 不是一个文件。')\n\n\n注意:\n\n- 该函数仅判断路径是否为文件,不判断文件是否存在。\n- 对于不存在的路径,该函数会返回 False。\n- 若要判断文件是否存在,可以使用 os.path.exists() 函数。


原文地址: https://www.cveoy.top/t/topic/pEfS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录