Python file name and file path operations,
Readme:
In our daily work, we often involve operations on file names and file paths. The OS standard module in python provides various functions for file operations, this article will introduce "getting current path", "getting all files and folders under current path", "deleting files", and "deleting directories/multiple directories" respectively ", "Check file/file path", "check whether the file path exists", "detach file path and file name", "detach file extension", "Get File Name" and "file path".
Import OS ''' to obtain the current path ''' cwd = OS. getcwd () print (cwd)
View Code
'''Print (OS. listdir ())
View Code
'''delete file'''os.remove('sw724.vaps')print(os.listdir())
View Code
''' Delete a single directory and multiple directories ''' OS. removedir () OS. removedir ()
View Code
''' Check whether it is a file/folder ''' print (OS. path. isfile ('/Users/liuxiaolong/PycharmProjects/untitled/sw724.vaps') print (OS. path. isdir ('/Users/liuxiaolong/PycharmProjects/untitled/sw724.vaps '))
View Code
''' Check whether the file path exists ''' print (OS. path. exists ('/Users/liuxiaolong/PycharmProjects/untitled/iiii '))
View Code
'''Separated file name separated extension ''' [dirname, filename] = OS. path. split ('/Users/liuxiaolong/PycharmProjects/untitled/sw724.vaps') print (dirname, "\ n", filename) [fname, fename] = OS. path. splitext ('/Users/liuxiaolong/PycharmProjects/untitled/sw724.vaps') print (fname, "\ n", fename)
View Code
''' Get file path get file name get current environment ''' print ("get pathname:", OS. path. dirname ('/Users/liuxiaolong/PycharmProjects/untitled/sw724.vaps') print ("get filename:", OS. path. basename ('/Users/liuxiaolong/PycharmProjects/untitled/sw724.vaps') print (OS. getenv)
View Code