SoFunction
Updated on 2024-12-10

Path stitching problems in python

python path splicing

Use:

  • () function: connects two or more pathname components
  • If one component is an absolute path, all components before it are discarded.
  • If the last component is empty, the generated path ends with a \ separator
def test2():
    s1, s2, s3 = 'home', 'courses', 'test'
    res = (s1, s2, s3)
    print(res)  # home\courses\test
    s2 = '/courses'
    res = (s1, s2, s3)
    print(res)  # /courses\test
    s1, s2, s3 = '\home', 'courses', 'test'
    res = (s1, s2, s3)
    print(res)  # \home\courses\test
    s1, s2, s3 = '\home', 'courses', ''
    res = (s1, s2, s3)
    print(res)  #\home\courses\

home\courses\test
/courses\test
\home\courses\test
\home\courses\

python path splicing error

ss = 'E:\\Cloud\\20200813105812L\\res\\1\\425'
a = '\\8_live_1962854245_export_files\\media'

c = (ss,a)
print(c)

The following result is obtained:

在这里插入图片描述

() function

Connects two or more pathname components:

There may be more than one parameter

Start counting from the right, encounter the first parameter starting with "/", start splicing, the parameter to the left of all the discarded

print("0:",('\\aaaa','bbbb',''))
print("0:",('aaaa','\\bbbb',''))
print("0:",('aaaa','bbbb','\\'))
print("0:",('aaaa','\\bbbb','\\'))
print("0:",('aaaa','/bbbb','\\'))
print("0:",('aaaa','/bbbb','/'))

in the end:
0: \aaaa\bbbb\
0: \bbbb\
0: \
0: \	
0: \
0: /

Start counting from the right, encounter the first parameter starting with "/", start splicing, the parameter to the left of all the discarded

print("1:",('aaaa','xxxxxx','./bbb',''))
print("1:",('./aaaa','xxxxxx','./bbb','./'))

in the end:
1: aaaa\xxxxxx\./bbb\
1: ./aaaa\xxxxxx\./bbb\./

With disk symbols,/,\, a variety of complex situations (before the official use of the test, you can also go to see the source code to see exactly how to parse)

# Backslash backslash
print("1:",('c:','bbb'))
print("1:",('c:','bbb/\\',''))

# Undisked
print("2:",('c','/bbb','')) # Will start with /bbb
print("2:",('c:','/bbb','')) # There's a backslash, but it still starts with a C: #
print("2:",('c:/','/bbb','')) # Multiple/only one

# No slash after the disk drive
print("3:",('c:','bbb',''))
print("3:",('c:/','bbb',''))

in the end:
1: c:bbb
1: c:bbb/\
2: /bbb\
2: c:/bbb\
2: c:/bbb\
3: c:bbb\
3: c:/bbb\

summarize

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.