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?
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With