当前位置:网站首页>os. path. Pits encountered during the use of join()

os. path. Pits encountered during the use of join()

2022-06-24 08:23:00 go_ flush

  • linux The way to splice paths is a slash /, win Concatenated backslash \
  • I am here os.path.join() It was found that If there is a slash or backslash at the beginning of the spliced path The splice path is truncated from the slash or backslash (win In the system ), If it is linux System The slash will be truncated , Backslash does not .
  • The code example is as follows :

win System

a_path_win = "http://www.baidu.com"
b_path_win = "data/img"
path_join = os.path.join(a_path_win, b_path_win) #  The way to search the path is the backslash \
print(f"sys = {
      sys.platform}")
print(f"path_join_win = {
      path_join}")

Printed results

sys = win32
path_join_win = http://www.baidu.com\data/img
c_path_win = "/data/img"
path_join_win_1 = os.path.join(a_path_win, c_path_win)
print(f"path_join_win_1 = {path_join_win_1}")

Printed results

path_join_win_1 = /data/img  #  Truncate at slash 
d_path_win = "\data\img"
path_join_win_2 = os.path.join(a_path_win, d_path_win)
print(f"path_join_win_2 = {
      path_join_win_2}")

Printed results

path_join_win_2 = \data\img #  Truncate at backslash 

Linux System

a_path = "http://www.baidu.com"
b_path = "data/img"
path_join = os.path.join(a_path, b_path)
print(f"{
      sys.platform}")
print(f"path_join = {
      path_join}")

Printed results

linux
path_join = http://www.baidu.com/data/img
c_path = "/data/img"
path_join_1 = os.path.join(a_path, c_path)
print(f"path_join_1= {
      path_join_1}")

Printed results

path_join_1= /data/img  #  Slashes are also truncated 
d_path = "\data\img"
path_join_2 = os.path.join(a_path, d_path)
print(f"path_join_2 = {
      path_join_2}")

Printed results

path_join_2 = http://www.baidu.com/\data\img  # Backslashes do not truncate , They can splice 

FAQ

os.path.join stay win The backslash and slash encountered in the system are truncated here , stay linux Slashes encountered under the system will be truncated , Backslash does not , Do you have to remove the slash or backslash at the beginning when splicing paths , Otherwise, the path cannot be found

原网站

版权声明
本文为[go_ flush]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240437270702.html