在Python中,我们可以使用os模块来处理路径操作。以下是一些优雅地使用路径的示例:
os.path.join()方法来连接路径,这样可以避免手动拼接路径字符串。import ospath1 = "/path/to/directory"path2 = "file.txt"full_path = os.path.join(path1, path2)print(full_path)获取当前工作目录:使用os.getcwd()方法来获取当前工作目录的路径。import oscurrent_dir = os.getcwd()print(current_dir)检查路径是否存在:使用os.path.exists()方法来检查路径是否存在。import ospath = "/path/to/directory"if os.path.exists(path): print("Path exists")else: print("Path does not exist")创建目录:使用os.makedirs()方法来创建目录。import osnew_dir = "/path/to/new/directory"os.makedirs(new_dir)获取文件名和目录名:使用os.path.basename()和os.path.dirname()方法来分别获取文件名和目录名。import ospath = "/path/to/directory/file.txt"filename = os.path.basename(path)dirname = os.path.dirname(path)print("Filename:", filename)print("Directory name:", dirname)通过这些方法,我们可以更加优雅地处理路径操作,使代码更加清晰和易读。


