在Python中,获取文件目录的方法有多种,以下是一些常用的方法:
1. 使用`os`模块获取当前工作目录:
import oscurrent_directory = os.getcwd()print("Current directory:", current_directory)
2. 使用`__file__`获取当前文件路径:
import oscurrent_file_path = os.path.abspath(__file__)print("Current file path:", current_file_path)
3. 使用`os.path.split()`方法获取文件所在目录:
import osfile_path = "path/to/your/file.txt"directory, filename = os.path.split(file_path)print("Directory:", directory)
4. 使用`os.path.dirname()`获取文件所在目录:

import osfile_path = "path/to/your/file.txt"directory = os.path.dirname(file_path)print("Directory:", directory)
5. 使用`os.path.realpath(__file__)`获取文件的绝对路径:
import osfile_path = os.path.realpath(__file__)print("Absolute file path:", file_path)
6. 使用`os.listdir()`获取目录文件列表:
import osdirectory = "." 当前目录file_list = os.listdir(directory)print("Files and directories in", directory + ":")for file in file_list:print(file)
7. 使用`pathlib`模块获取文件路径:
from pathlib import Pathfile_path = Path(__file__).resolve()print("File path:", file_path)
