python path splicing os.path.join() function

Function: string.join() 

There are two functions, join() and os.path.join(), in Python. The specific functions are as follows:
join(): Concatenate string arrays. Concatenate elements in strings, tuples, and lists with specified characters (delimiters) to generate a new string
os.path.join(): Return after combining multiple paths

1. Function description
1. join() function
Syntax : 'sep'.join(seq)
parameter description
sep: separator. Can be empty
seq: element sequence, string, tuple, dictionary to be concatenated The
above syntax is: with sep as the separator, combine all elements of seq into a new string
Return value: return a string separated by the separator sep String
generated after connecting each element


The os.path.join() function is used to concatenate file paths with paths. Multiple paths can be passed in the os.path.join() function:

need to import import os

 
 

default=os.path.join(os.getenv('TEST_TMPDIR', '/tmp'),'tensorflow/mnist/input_data')

Read and set environment variables: os.getenv() and os.putenv()

Get the os.getenv('TEST_TMPDIR', '/tmp')temporary folder, the default is/tmp

os.path.join()函数:

  • The first parameter starting with "/" starts splicing, and all the previous parameters are discarded.

  • One of the above cases is the first. In the case of the previous guarantee, if there is a parameter starting with "./", it will be spliced ​​from the previous parameter of the parameter starting with "./"

import them

print("1:",os.path.join('aaaa','/bbbb','ccccc.txt'))

print("2:",os.path.join('/aaaa','/bbbb','/ccccc.txt'))

print("3:",os.path.join('aaaa','./bbb','ccccc.txt'))   

The output is

1: /bbbb\ccccc.txt
2: /ccccc.txt
3: aaaa\./bbb\ccccc.txt


#合并目录

>>> import os
>>> os.path.join('/hello/','good/boy/','doiido')
'/hello/good/boy/doiido'

To sum up: In fact, it is only two different ways of writing, and the degree of splicing can achieve the same splicing effect. Write to your liking

print("1:",os.path.join('aaaa','/bbbb','ccccc.txt'))print("2:",os.path.join('/aaaa','/bbbb','/ccccc.txt'))os.path.join('/hello/','good/boy/','doiido')只有一个以”/”开头的,参数从它开始往后拼接,之前的参数全部丢弃有多个以”/”开头的参数,从最后”/”开头的的开始往后拼接,之前的参数全部丢弃。
 
 
 
 
print("3:",os.path.join('aaaa','./bbb','ccccc.txt'))
若出现”./”开头的参数,会从”./”开头的参数的上一个参数开始拼接




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325876895&siteId=291194637