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)
parent_directory=Path('/path/to')directory_name='new_directory'directory_path=parent_directory/directory_nameprint(directory_path) 1. 2. 3. 4. 5. 6. 7. 在这个例子中,我们使用/运算符将父目录路径/path/to和目录名new_directory连接起来。最终,我们得到的目录路径为/path/to/new_directory。 3. 检...
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.')上面...
parent_directory = os.path.dirname(os.path.dirname(absolute_path)) print("文件所在的父目录为:", parent_directory) 5、如果我们想要获取文件所在的根目录,我们可以使用os.path.dirname()函数三次,我们可以使用以下代码来获取文件所在的根目录: root_directory = os.path.dirname(os.path.dirname(os.path.di...
从上面代码来看我的python版本3.12.5 ,其Path()和Path('.')都表示当前工作目录 😄使用除法操作连接目录和文件名: frompathlibimportPath# 创建Path对象表示目录# 只是创建了路径对象,并没有真的在文件系统中创建这个目录parent_dir = Path(r"D:\py_related\test\new_directory")# 创建Path对象表示文件名file_...
:{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...
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: 不带后缀的文件名 ...
import os # 使用相对路径切换目录 os.chdir("../parent_directory") # 使用绝对路径切换目录 os.chdir("/absolute/path/to/directory")异常处理 如果提供的路径不存在或由于其他原因无法切换目录,chdir函数将引发一个FileNotFoundError异常。因此,在实际应用中,建议对chdir函数的使用进行异常处理:或者...