current_path = os.path.dirname(os.path.abspath(__file__)) # 计算相对路径并读取文件 relative_path = os.path.join(current_path, "relative/path/to/file.txt") with open(relative_path, 'r') as file: file_contents = file.read() print(file_contents) 在上述代码中,我们首先获取当前脚本的路...
参数path:要获取绝对路径的字符串路径。用法示例:import os# Windows路径示例path1 = r'relative\path\file.txt'path2 = r'C:\path\to\file.txt'abs_path1 = os.path.abspath(path1)abs_path2 = os.path.abspath(path2)print(abs_path1) # 输出: C:\current\directory\relative\path\file.txtprint...
importos# 文件路径file_path='path/to/file.txt'# 参考路径reference_path='path/to/reference/'# 获取文件的绝对路径absolute_path=os.path.abspath(file_path)# 获取参考路径的绝对路径absolute_reference_path=os.path.abspath(reference_path)# 计算相对路径relative_path=os.path.relpath(absolute_path,absolute...
对于绝对路径,可以直接传入该路径字符串作为参数,如: from pathlib import Path absolute_path = Path("/path/to/file") print(absolute_path) 复制代码 对于相对路径,可以使用当前工作目录作为基础路径,然后传入相对路径的字符串,如: from pathlib import Path base_path = Path.cwd() # 获取当前工作目录 relat...
Path.exists(): 检查给定的路径是否存在。 Path.stat(): 获取文件的状态信息(如大小、修改时间等)。 示例: frompathlibimportPath# 获取当前工作目录current_directory = Path.cwd()print("当前工作目录:", current_directory)# 使用相对路径relative_path ="subfolder/file.txt"absolute_path = current_directory...
# 假设我们要保存的相对路径是相同的relative_path_to_save=relative_path# 将相对路径保存到文件withopen('relative_path.txt','w')asfile:file.write(relative_path_to_save)print("相对路径已保存到'relative_path.txt'") 1. 2. 3. 4. 5.
from pathlib import Pathpath = Path('file.txt')# 创建一个新文件path.touch()# 重命名文件path.rename('new_file.txt')# 删除文件path.unlink()# 创建一个新目录path.mkdir()# 创建一个新目录,如果父目录不存在则递归创建path = Path('path/to/new/directory')path.mkdir(parents=True, exist_ok=...
relative_path = file_path.relative_to(base_path) print(relative_path) 输出结果为“data/file.txt”。 3. sys模块 sys模块是Python中用于访问与Python解释器交互的变量和函数的模块。它提供了一些变量来获取文件的相对路径。 3.1 sys.path[0] sys.path[0]变量用于获取当前脚本所在的目录的路径。 例如,如果我...
文件path.rename('new_file.txt')# 删除文件path.unlink()# 创建一个新目录path.mkdir()# 创建一个新目录,如果父目录不存在则递归创建path=Path('path/to/new/directory')path.mkdir(parents=True,exist_ok=True)# 删除空目录path.rmdir()# 递归删除目录及其所有内容path=Path('path/to/directory')path....
full_path = os.path.join('directory', 'subdirectory', 'file.txt')Python 复制 最后,获取文件或目录的绝对路径:absolute_path = os.path.abspath('relative/path/to/file')Python 复制 借助该os模块,在 Python 中处理目录和文件操作变得轻而易举,从而可以有效地管理和操作项目的结构。现实场景:何时访问...