Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

List Files in Python

import os

# returns name of all files & directory exist in current location
files_dir = os.listdir('./blogs')
# './blogs' is the directory in the current location
print(files_dir)
only_files = []
for i in files_dir:
    if os.path.isfile('./blogs/'+i):
        only_files.append(i)
only_dir = []
for i in files_dir:
    if os.path.isdir('./blogs/'+i):
        only_dir.append(i)
print('-'*15)
print(only_files) # prints all files
print('-'*15)
print(only_dir) # prints all directories
"""
OUTPUT: 
['1.txt', '2.txt', '3.txt', '4.txt', '5.txt', '6.txt', '7.txt', '8.txt', 'Test Directory 1', 'Test Directory 2']
---------------
['1.txt', '2.txt', '3.txt', '4.txt', '5.txt', '6.txt', '7.txt', '8.txt']
---------------
['Test Directory 1', 'Test Directory 2']
"""
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #List #Files #Python
ADD COMMENT
Topic
Name
6+3 =