current_dir)# 拼接路径file_path=os.path.join(current_dir,"file.txt")print("文件路径:",file_path)# 获取绝对路径absolute_path=os.path.abspath(file_path)print("绝对路径:",absolute_path)# 获取相对路径relative_path=os.path.relpath(absolute_path,start=current_dir)print("相对路径:",relative_path...
用法示例:import os# Windows路径示例path1 = r'relative\path\file.txt'path2 = r'C:\path\to\file.txt'abs_path1 = os.path.
下面是这个实现过程的完整代码示例: importos# 获取当前文件所在的目录current_dir=os.path.dirname(__file__)# 定义相对路径relative_path='new_folder'# 组合当前目录和相对路径folder_path=os.path.join(current_dir,relative_path)# 创建文件夹os.makedirs(folder_path) 1. 2. 3. 4. 5. 6. 7. 8. 9...
Path.exists(): 检查给定的路径是否存在。 Path.stat(): 获取文件的状态信息(如大小、修改时间等)。 示例: frompathlibimportPath# 获取当前工作目录current_directory = Path.cwd()print("当前工作目录:", current_directory)# 使用相对路径relative_path ="subfolder/file.txt"absolute_path = current_directory ...
()) #rstrip()用于删除字符串末尾的空白 #通过路径打开,相对路径打开统一文件夹的文件,绝对路径打开绝对位置的文件 relative_file_path = '\something\somenting\filename' with open(relative_file_path): as file1 file_path = 'C:\something\somrthing\filename.扩展名' with open(file_path) as file2:...
if path.exists(): print('文件存在') else: print('文件不存在') 复制代码 检查是否为文件或目录: if path.is_file(): print('是文件') elif path.is_dir(): print('是目录') 复制代码 获取绝对路径和相对路径: # 获取绝对路径 absolute_path = path.absolute() # 获取相对路径 relative_path ...
To join the information from __file__ onto your relative path, there's a newer option than os.path interfaces available since 2014: from pathlib import Path here = Path(__file__).parent fname = here / "test.txt" with fname.open() as f: ... pathlib was added to Python in ...
home() / Path('my/relative/path') WindowsPath('C:/Users/Al/my/relative/path') os.path模块也有一些与绝对和相对路径相关的有用函数: 调用os.path.abspath(path)将返回参数字符串的绝对路径。这是一种将相对路径转换成绝对路径的简单方法。 如果参数是绝对路径,调用os.path.isabs(path)将返回True,如果是...
print(file_contents) 另外,您还可以使用__file__变量来获取当前脚本的路径,并根据该路径计算相对路径。 import os # 获取当前脚本的路径 current_path = os.path.dirname(os.path.abspath(__file__)) # 计算相对路径并读取文件 relative_path = os.path.join(current_path, "relative/path/to/file.txt")...
file_path = os.path.join(current_dir, relative_path) # 创建文件 with open(file_path, 'w') as file: pass # 这里什么都不做,只是创建一个空文件 # 调用函数创建文件 create_file('example.txt') 在上述示例中,create_file()函数接受一个相对路径作为参数,并将其与当前工作目录拼接成完整的文件路径...