python directory and file operations

 Disclaimer: This article is a blogger original article, welcome to reprint, and please indicate the source. Contact: [email protected]

 A separation path

fpath,fname=os.path.split(r'E:\projects\abc\def.png')

'E:\\projects\\abc', 'def.png'

extension name

os.path.split(r'E:\projects\abc\def.png')[-1].split('.')[-1]

png

fpath,fname=os.path.split(r'E:\projects\abc')

'E:\\projects', 'abc'

Second, the synthesis route

pa = os.path.join(r'E:\projects\abc', 'def.png')

E:\\projects\\abc\\def.png

pa = os.path.join(r'E:\projects', 'abc', 'def.png')

E:\\projects\\abc\\def.png

 Third, determine the directory / file exists

os.path.exists()

Fourth, create a directory

os.makedirs (fpath) # may have been created at all levels of directory
os.mkdir (fpath) # can be created only last a directory

Fifth, delete directory

shutil.rmtree (fpath) # can delete non-empty directory

os.rmdir (path) can be deleted directory is not empty #

Six lists subdirectories and files in the directory

os.listdir (R ': \ projects')  

Seven listed subdirectories

[F for f in os.listdir (file_path) if os.path.isdir (os.path.join (file_path, f))] # directory name only

[os.path.join(file_path, f) for f in os.listdir(file_path) if os.path.isdir(os.path.join(file_path, f))]  #  全路径

Eight, list files in a directory

[F for f in os.listdir (file_path) if os.path.isfile (os.path.join (file_path, f))] # Only the file name

[Os.path.join (file_path, f) for f in os.listdir (file_path) if os.path.isfile (os.path.join (file_path, f))] # absolute file path

Nine, delete files

os.remove ()

Ten, all subdirectories listed in the directory

path = r'E:\soft'
for dirpath, dirnames, filenames in os.walk(path):
    for dirname in dirnames:
        print(os.path.join(dirpath, dirname))

XI, all files listed in the directory

path = r'E:\soft'
for dirpath, dirnames, filenames in os.walk(path):
    for filename in filenames:
        print(os.path.join(dirpath, filename))

Twelve, directory traversal

path = r'E:\soft'
for dirpath, dirnames, filenames in os.walk(path):
    print(dirpath, dirnames, filenames)

 

Guess you like

Origin www.cnblogs.com/zhengbiqing/p/11072820.html