directory_path = os.path.dirname(__file__) print("当前文件所在目录的路径:", directory_path) 在上述代码中,我们使用os.path.dirname()函数获取当前文件所在目录的路径,并将结果保存在变量directory_path中。 os.path.basename(): 获取文件名 os.path.basename()函数用于获取文件路径的文件名。 # 获取当前...
os.path.dirname()函数用于获取文件路径的目录名。 代码语言:python 代码运行次数:0 运行 AI代码解释 # 获取当前文件所在目录的路径 directory_path = os.path.dirname(__file__) print("当前文件所在目录的路径:", directory_path) 在上述代码中,我们使用os.path.dirname()函数获取当前文件所在目录的路径,并将...
print(os.path.exists(r'/path/to/your/directory')) # 检查A\message.txt文件是否存在 print(os.path.exists(r'A\message.txt'))os.path.dirname()方法用于从指定路径中获取目录名,返回上一级的目录 # os.path.dirname() 方法用于从指定路径中获取目录名,返回上一级的目录 # Path path = r'\path\to...
new_dir ='/path/to/new/directory'os.chdir(new_dir) os.path.join(path1, path2, ...):将多个路径组合成一个完整的路径,会根据操作系统自动处理路径分隔符。 importos path = os.path.join('home','user','documents')print(path)# 在 Unix 系统上输出 'home/user/documents' os.path.abspath(pat...
参数path:要进行分割的字符串路径。返回值:返回包含目录部分和文件名部分的元组 (dirname, basename)。用法示例:import os# Windows路径示例path1 = r'C:\path\to\file.txt'path2 = r'C:\path\to\directory'split1 = os.path.split(path1)split2 = os.path.split(path2)print(split1) # 输出: (...
1、os.path 方法 import os import sys current_directory = os.path.dirname(os.path.abspath(__file__)) print(current_directory) 2、os.path.abspath 方法 import os import sys root_path = os.path.abspath(os.path.dirname(current_directory) + os.path.sep + ".") ...
在上述代码中,我们使用os.path.dirname()函数获取当前文件所在目录的路径,并将结果保存在变量directory_path中。 os.path.basename(): 获取文件名 os.path.basename()函数用于获取文件路径的文件名。 # 获取当前文件的文件名file_name = os.path.basename(__file__)print("当前文件的文件名:", file_name) ...
用法示例:import os# Windows路径示例path1 = r'C:\path\to\file.txt'path2 = r'C:\path\to\directory'basename1 = os.path.basename(path1)basename2 = os.path.basename(path2)print(basename1) # 输出: file.txtprint(basename2) # 输出: directory# Linux路径示例path3 = '/path/to/file....
以下是使用os.chdir()函数进入目录的示例: 代码语言:txt 复制 import os # 指定要进入的目录路径 directory_path = '/path/to/your/directory' # 使用os.chdir()函数进入该目录 os.chdir(directory_path) # 验证是否成功进入目录 print(os.getcwd()) # 输出当前工作目录,应该与你指定的路径一致 ...
如果你只想查看文件,可以使用os.path.isfile()函数来检查每个条目是否为文件: import os # 指定要查看的目录路径 directory_path = '/path/to/your/directory' # 使用os.listdir()函数获取目录内容 directory_contents = os.listdir(directory_path) # 遍历目录内容并打印文件名 for item in directory_contents:...