current_dir=sys.path[0]parent_dir=sys.path[1]print("当前目录:",current_dir)print("父目录:",parent_dir) 1. 2. 3. 4. 5. 6. 7. 在上述代码中,sys.path[0]表示当前脚本所在的目录。sys.path[1]表示该目录的父目录。输出结果如下: 当前目录: /path/to/current_directory 父目录: /path/to/...
parent_directory =os.path.dirname(current_directory)print("当前目录:", current_directory)print("上一级目录:", parent_directory)
importos# 获取当前文件所在的父级目录current_file_path=os.path.abspath(__file__)parent_directory=os.path.dirname(current_file_path) 1. 2. 3. 4. 5. 上述代码中,首先导入了os模块。然后,使用os.path.abspath(__file__)获取当前文件的绝对路径,__file__表示当前文件的文件名。接着,使用os.path.di...
name) # python3print(path.parent) # /usr/binprint(path.parts) # ('/', 'usr', 'bin', 'python3')if path.exists(): if path.is_dir(): print('Path is a directory.') elif path.is_file(): print('Path is a file.')else: print('Path does not exist.')上面...
:{file_path.is_dir()}") #判断文件是否为文件 print(f"is this a file? :{file_path.is_file()}") #返回结果: #is this exist? :True #is this a directory? :False #is this a file? :True 4、遍历文件 指定目录下的所有文件夹,通过上面的判断,可以筛选出来:#获取父目录 parent = curren...
从上面代码来看我的python版本3.12.5 ,其Path()和Path('.')都表示当前工作目录 😄使用除法操作连接目录和文件名: frompathlibimportPath# 创建Path对象表示目录# 只是创建了路径对象,并没有真的在文件系统中创建这个目录parent_dir = Path(r"D:\py_related\test\new_directory")# 创建Path对象表示文件名file_...
print(path.parent) # /usr/bin print(path.parts) # ('/', 'usr', 'bin', 'python3') if path.exists(): if path.is_dir(): print('Path is a directory.') elif path.is_file(): print('Path is a file.') else: print('Path does not exist.') ...
import os # 使用相对路径切换目录 os.chdir("../parent_directory") # 使用绝对路径切换目录 os.chdir("/absolute/path/to/directory")异常处理 如果提供的路径不存在或由于其他原因无法切换目录,chdir函数将引发一个FileNotFoundError异常。因此,在实际应用中,建议对chdir函数的使用进行异常处理:或者...
import os# 改变当前工作目录到指定路径os.chdir('path/to/directory')在这个例子中,我们使用os模块调用了chdir函数,并传入了一个目录路径作为参数。这将把当前工作目录更改为指定的目录。例如,可以将路径设置为'/home/user/'或'../parent_directory/'等。改变目录进行文件处理 通过改变当前工作目录,我们可以方便...
print(path) # . print(path.absolute() / 'test' / 'data.txt') # F:\spug-3.0\spug-3.0\spug_api\test\data.txt pathlib的基本使用 Path类的常用属性和方法 descriptor: parts: 每一层路径 parent: 父目录 parents: 所有父目录 stem: 不带后缀的文件名 ...