Summary of Operation Methods of python File Path

  • 2021-08-31 08:29:37
  • OfStack

In python, files are used 10 points frequently. This article will introduce the operation of python file path: get the specified file path, get the current file name, judge whether the file path exists, get all the files under the specified folder, and get the file suffix, splicing path and file name.

1. Get the specified file path: os. path. dirname (file name with path)

Find processing files to call os library, and openpyxl1 sample, first use import import.


import os
file = r'e:\python\ Delete minimum value .xlsx'
pwd = os.path.dirname(file)
print(pwd)

The running result is:


e:\python

It can also be extracted from the list after separating file names: os. path. split (filename with path) [0]

2. Get the current file name: os. path. dasename (file name with path)


import os
file = r'e:\python\ Delete minimum value .xlsx'
pwdn = os.path.basename(file)
print(pwdn)

The running result is:

Remove minimum value. xlsx

It can also be extracted from the list after separating file names: os. path. split (filename with path) [1]

3. Judge whether the file path exists: os. path. exists (file name with path)


import os
file = r'e:\python\ Delete minimum value .xlsx'
pwdbool = os.path.exists(file)
print(pwdbool)

The running result is:

true

If the given path file does not exist, false is returned

4. Get all files in the specified folder: print (os. listdir (folder path))


import os
pwdns = os.listdir(r'e:\python')
print(pwdns[1])

Run results:

. py is the second file (or folder) name under the 'e:\ python' folder.

5. Get the file suffix: os. path. splitext (file name)


import os
pdn= os.path.splitext( 'Test .py')
print(pdn[1])

Run results:

. py, if the last sentence is changed to print (pdn [0]), the file name is obtained.

6. Splice path and file name: os. path. join (path, file name)


f2 = os.path.join(f1,  'Summary .xlsx')

Run results:

'e:\ python\ Summary\ Summary. xlsx'


Related articles: