一、Python OS 文件/目录方法 Python的os模块提供了与操作系统交互的方法,包括文件和目录的操作。以下是一些常用的os模块中的文件/目录方法: 目录操作 os.getcwd(): 返回当前工作目录的路径。 import os current_directory = os.getcwd() print(current_directory) os.chdir(path): 改变当前工作目录到指定的路径。
返回表示当前目录(current directory)的字符串,win系统可能就是返回一个点(.)。
我们可以使用os模块中的方法来进入当前目录的下一级目录。 importos# 获取当前工作目录current_dir=os.getcwd()print("Current directory:",current_dir)# 进入下一级目录next_dir=os.path.join(current_dir,'next_level')os.chdir(next_dir)# 获取当前工作目录current_dir=os.getcwd()print("Current directory ...
importosimportpandasaspddefload_csv_file(file_name):# 获取当前工作目录current_directory=os.getcwd()# 构建完整的文件路径file_path=os.path.join(current_directory,file_name)# 读取 CSV 文件try:data=pd.read_csv(file_path)print(f"{file_name}文件已成功加载。")returndataexceptFileNotFoundError:print...
import os Python 复制 如果你想获取当前工作目录,请使用:current_directory = os.getcwd()Python 复制 要更改当前工作目录:os.chdir('/path/to/directory')Python 复制 列出目录的内容很简单:contents = os.listdir('/path/to/directory')Python 复制 创建新目录可以通过两种方式完成。对于单个目录:os.mkdir(...
当前工作目录 (current working directory)是文件系统当前所在的目录,如果命令没有额外指定路径,则默认为当前工作目录。 1 2 3 4 5 6 7 8 9 10 11 12 importos # 当前文件的绝对路径 print(os.path.abspath(__file__))# 输出:/home/wp/st_detection/download_code/YOLOv5/ultralytics_yolov5_master/tra...
current_directory = os.getcwd() print(f"当前工作目录是: {current_directory}") ``` 上述代码会输出当前工作目录的绝对路径。这个路径通常是你启动Python解释器时所在的目录,但它也可能会被你的开发环境或IDE设定为特定的路径。 在某些情况下,我们可能需要更改当前工作目录,例如当我们想让程序在特定目录下创建或...
importos#获取当前工作目录current_dir =os.getcwd()print(f"当前工作目录: {current_dir}")#更改当前工作目录到指定路径new_dir ="/path/to/your/directory"os.chdir(new_dir)#验证是否已经切换到新目录new_current_dir =os.getcwd()print(f"新的当前工作目录: {new_current_dir}")...
import os current_directory = os.getcwd() print(current_directory) 复制代码 创建新目录: import os new_directory = "new_folder" os.mkdir(new_directory) # 如果目录已存在,会抛出FileExistsError异常 复制代码 创建多层级目录: import os path = "parent/child/subchild" os.makedirs(path, exist_ok...
1.Path.cwd()和Path.home() Path.cwd()返回一个新的表示当前目录的路径对象(和 os.getcwd() 返回的相同) Path.home()返回一个表示当前用户家目录的新路径对象(和 os.path.expanduser() 构造含 ~ 路径返回的相同) #!/usr/bin/env python3frompathlibimportPathprint(f"Current directory: {Path.cwd()}"...