Python 设定工作目录 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}")...
获取当前文件夹路径及父级目录: importos current_dir= os.path.abspath(os.path.dirname(__file__))print(current_dir)#F:\project\priticecurrent_dir1= os.path.dirname(__file__)print(current_dir1)#F:/project/priticeparent_path=os.path.dirname(current_dir1)print(parent_path)#F:/projectparent...
1. 2. 3. 2. 读取配置文件 接下来,我们可以从当前文件的目录中读取配置文件。假设配置文件为config.ini,我们可以使用configparser模块来读取: importconfigparser config_file=os.path.join(current_dir,'config.ini')config=configparser.ConfigParser()config.read(config_file)# 使用配置文件中的值value=config.get...
importos# 查看当前工作目录current_dir=os.getcwd()print(f"当前工作目录:{current_dir}")# 修改当前工作目录new_dir="/path/to/new_directory"os.chdir(new_dir)# 获取文件所在目录file_path="/path/to/file.txt"file_dir=os.path.dirname(file_path)print(f"文件所在目录:{file_dir}")# 读取文件的默...
1. 使用os.getcwd()函数可以获取当前工作目录的路径。这个路径是指你当前运行Python脚本的目录。import oscurrent_dir = os.getcwd()print(current_dir)2. 使用os.path.abspath()获取文件的绝对路径。import osfile_path = os.path.abspath("file.txt")print(file_path)3. 使用os.path.dirname()获取文件的...
current_dir = os.getcwd() print(current_dir) ``` 2. 创建文件夹 可以使用 `os.mkdir()` 方法创建新的文件夹: ```python import os new_folder = "new_folder" os.mkdir(new_folder) ``` 3. 检查路径是否存在 使用`os.path.exists()` 方法可以检查路径是否存在: ...
可以使用os模块来获取当前脚本文件的绝对路径,并通过处理路径字符串来获取项目根目录。 下面是一种常见的方法: import os # 获取当前脚本文件的绝对路径 current_path = os.path.abspath(__file__) # 获取当前脚本文件所在的目录路径 current_dir = os.path.dirname(current_path) # 获取项目根目录 project_dir...
print("当前工作目录是否是目录:", current_dir.is_dir()) 2. Path操作方法 Path类还提供了丰富的路径操作方法,包括路径拼接、文件/目录创建、文件/目录移动/删除等操作。 示例代码如下: from pathlib import Path # 创建目录和文件 new_dir = Path('new_directory') ...
print(current_dir) “` 2. 使用os模块中的`os.chdir(path)`方法可以改变当前的工作目录为指定的路径。例如: “` import os os.chdir(‘/path/to/directory’) “` 在默认情况下,Python文件的保存路径就是当前工作目录。当你在IDE(集成开发环境)中创建一个新的Python文件并保存,它会自动保存在当前工作目录下...
current_dir = os.getcwd()print(current_dir) # 输出当前工作目录的路径 上述代码打印出当前工作目录的路径,例如'C:/Users/Alice/Documents'。4. 使用相对路径切换目录 除了使用绝对路径外,我们还可以使用相对路径来切换目录。相对路径是相对于当前工作目录的路径,可以方便地切换到当前目录的子目录或父目录。示...