Detailed explanation of os.path.join() in Python

os.path.join() is useful when you need to build a file path. This method will use the correct path separator according to your operating system (for example, backslash\ on Windows, forward slash/) to connect the various parts of the path. This way you can ensure that your code works correctly on different operating systems.

The following is the basic usage of the os.path.join() method:

import os

# 示例路径部分
folder = "my_folder"
filename = "example.txt"

# 使用 os.path.join() 构建完整路径
full_path = os.path.join(folder, filename)

# 打印结果
print(full_path)

In this example, full_path will be the full path of folder and filename merged. No matter what operating system you're running your code on, os.path.join() will use the appropriate path separator for that operating system. For example, if you were running this code on Windows, full_path might be a string similar to "my_folder\example.txt".

Also,os.path.join() can accept multiple parameters, concatenating them into a single path. For example:

import os

# 示例路径部分
parent_folder = "parent_folder"
child_folder = "child_folder"
filename = "example.txt"

# 使用 os.path.join() 构建完整路径
full_path = os.path.join(parent_folder, child_folder, filename)

# 打印结果
print(full_path)

This will produce a path similar to "parent_folder/child_folder/example.txt", with the path separator changing depending on the operating system.

Let’s give another example to illustrate its most correct usage and incorrect usage:

# -*- coding: utf-8 -*-

import os

path1 = os.path.join('D:/temp/', 'static')  # 最正确的用法

path2 = os.path.join('D:/temp/', '/static')  # 错误的用法

path3 = os.path.join('D:/temp', 'static')  # 根据是Windows系统还是UNIX系统自动添加分割符

print('正确的用法的结果:', path1)
print('错误的用法的结果:', path2)
print('根据系统决定用哪个分割符的结果:', path3)

The running results are as follows:

Insert image description here

Guess you like

Origin blog.csdn.net/wenhao_ir/article/details/134497576