Python reads files in folders and files in subfolders

  1. os.listdir()Read the file name and subfolder name under the target folder, and will not recursively read the subfolder

    names = os.listdir(".\\")
    for i in names:
    	print(i)
    	path = os.path.join(".\\", i) ##重要
    	if os.path.isdir(path):
    		print(path, " is dir")
    	if os.path.isfile(path):
    		print(path, " is file")
    
  2. Method 1: root, dirs, files = os.walk()Recursively read all files under the folder and subfolders . Method 2: You can also use os.listdir() to judge that it is a folder and then write a recursive program by yourself in os.listdir()

    for root,dirs,files in os.walk(dirname):
        for file in files:
            path = os.path.join(root,file)
            print(path)
    
  3. example

    import os
    
    dirname = ".\..\dir1"
    #判断文件夹dirname是否存在
    if not os.path.exists(dirname):
        print("error: folder \"", dirname, "\" not exits!")
        sys.exit()
    ## 读取文件夹dirname下的文件和子文件夹,并判断是文件还是文件夹
    
    ##只读取文件夹下一级文件名和子文件夹,并不会列举子文件夹里文件
    names = os.listdir(dirname)
    for name in names:
        path = os.path.join(dirname, name)  ##很有必要,不然结果会不对
        if os.path.isdir(path): #文件夹
            print(name, " is dir")
        if os.path.isfile(path): #文件
            print(name, " is file")
            
    # 递归获得文件夹和子文件夹下所有文件名
    for root,dirs,files in os.walk(dirname):
        for file in files:
            path = os.path.join(root,file)
            print(path)
    

Guess you like

Origin blog.csdn.net/qq_41253960/article/details/128267990