Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i list folder in directory [duplicate]

This is my code :

import os

def get_file():
    files = os.listdir('F:/Python/PAMC')
    print(files)

    for file in files:
        print(file)

get_file()

How do i list only folders in a directory in python?

like image 518
MOHS3N Avatar asked Apr 17 '18 16:04

MOHS3N


People also ask

How do I compare two folders for duplicates?

Click on the “Select Files or Folders” tab in the far left, to start a new comparison. Each comparison you run opens in a new tab. To start a new comparison, click on the “Select Files or Folders” tab in the far left, change the targets and click “Compare” again.


1 Answers

Tried and tested the below code in Python 3.6

import os

filenames= os.listdir (".") # get all files' and folders' names in the current directory

result = []
for filename in filenames: # loop through all the files and folders
    if os.path.isdir(os.path.join(os.path.abspath("."), filename)): # check whether the current object is a folder or not
        result.append(filename)

result.sort()
print(result)

#To save Foldes names to a file.
f= open('list.txt','w')
for index,filename in enumerate(result):
    f.write("%s. %s \n"%(index,filename))

f.close()

Alternative way:

import os
for root, dirs, files in os.walk(r'F:/Python/PAMC'):
    print(root)
    print(dirs)
    print(files)

Alternative way

import os
next(os.walk('F:/Python/PAMC'))[1]
like image 157
Ramineni Ravi Teja Avatar answered Oct 20 '22 00:10

Ramineni Ravi Teja