Jun 24, 2018

Read direcory in Python

'''
    File name: dir_read.py
    Author: Prabhath Kota
    Date: June 22, 2018
    Python Version: 2.7
'''

import glob
import os

rootdir = 'Exercise'

print '------------glob------------------'
#List only python files
glob_root_dir = os.path.join(rootdir, '*.py')
arr_list = glob.glob(glob_root_dir)
for each_file in arr_list:
    print(each_file)

print '------------listdir------------------'
#List only txt files
for each_file in os.listdir(rootdir):
    file_path = os.path.join(rootdir,each_file)
    file_base, extension = os.path.splitext(file_path)
    #print extension
    if os.path.isfile(file_path) and extension == '.txt':
        print each_file
print '######'
for each_file in os.listdir(rootdir):
    print(each_file)

print '------------os.walk------------------'
for root, dirs, files in os.walk(rootdir):
    print '---Each loop'
    print root
    if dirs:
        print '###### Dirs'
        for file in dirs:
            print os.path.join(root, file)
    print '###### Files'
    for file in files:
        print os.path.join(root, file)

No comments:

Post a Comment