在 Python 中,可以使用 os 模块来操作文件路径。以下是一些常用的操作文件路径的方法:
import oscurrent_dir = os.getcwd()print(current_dir)获取文件的绝对路径:import osfile_path = os.path.abspath('file.txt')print(file_path)拼接文件路径:import ospath = os.path.join('dir1', 'dir2', 'file.txt')print(path)检查文件或目录是否存在:import osif os.path.exists('file.txt'): print('File exists')else: print('File does not exist')获取文件名和文件扩展名:import osfile_name = os.path.basename('path/to/file.txt')file_extension = os.path.splitext(file_name)[1]print(file_name, file_extension)这些是一些常用的操作文件路径的方法,可以根据具体需求进行调整和扩展。


