Python common modules os.path ——File and path operation

Time:2020-6-24

os.path.abspath(path)

Enter relative path, return absolute path

Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import os
>>> print(os.path.abspath("."))
C:\Users914\AppData\Local\Programs\Python\Python37

os.path.basename(path)

Returns the file or directory name at the end of the path. String processing alone does not control whether the path exists

>>> import os
>>> os.path.basename("E:\abc\efg.txt")
'efg.txt'

os.path.dirname(path)

and os.path.basename Instead, the last file or directory name is removed from the return path, which is a simple string processing

>>> import os
>>> os.path.dirname("E:\abc\efg.txt")   
'E:\abc'

os.path.split(path)

Simple string processing, split path, return tuple composed of directory name and file name

>>> import os
>>> os.path.split("E:\abc\efg.txt")   
('E:\abc', 'efg.txt')

os.path.splitext(path)

Simple string processing, split path, return tuple composed of file name and extension

>>> import os
>>> os.path.splitext("E:\abc\efg.txt")   
('E:\abc\efg', '.txt')

os.path.join(dirpath,filename)

Splice the path and file name, and use the corresponding path separator automatically according to the operating system. For windows, use “” and for Linux, use “” / “”

>>> import os
>>> os.path.splitext("E:\abc\efg.txt")   
('E:\abc\efg', '.txt')

os.path.exists(path)

True or false to determine whether the file or directory exists

>>> import os
>>> os.path.exists("E:\abc\efg.txt")
False

os.path.isdir(path)

Determine whether the path is a folder. If the path does not exist, return false

>>> import os
>>> os.path.isdir("E:\abc\efg.txt")
False

os.path.isfile(path)

Judge whether the path is a file. If the path does not exist, return false

>>> import os
>>> os.path.isfile("E:\abc\efg.txt")
False

os.path.getsize(path)

Get file size, unit byte. If the file does not exist, an error will be reported. It cannot be directly used for folders

>>> import os
>>> os.path.getsize("D:\2019-11-07.txt")
5973

os.path.getctime(path)

Get file creation time

os.path.getmtime(path)

Get the last modification time of the file

os.path.getatime(path)

Get file last access time