Showing posts with label python_glob. Show all posts
Showing posts with label python_glob. Show all posts

Sep 19, 2019

Python glob vs glob recursive - loop directory

import glob

p = glob.glob('*.py')
print(p)
print(len(p)) #17

#single star - all files in current dir
p = glob.glob('*', recursive=True)
print(p)
print(len(p)) #20

#double star - all folders and files recursively in current dir
p = glob.glob('**', recursive=True)
print(p)
print(len(p)) #22


"""
Output:
['timeit_test.py', 'args_kwargs.py', 'fibonacci.py', 'shallow_vs_deep_copy.py', 'inheritance_example.py', 'python_closure.py', 'super_test.py', 'date_example.py', 'contextlib_example.py', 're_compile_vs_match.py', 'iterator_example.py', 'str_repr_eval.py', 'generator_example.py', 'init_vs_call.py', 'main.py', 'filter_map_reduce.py', '_test_runner.py']
17

['timeit_test.py', 'args_kwargs.py', 'fibonacci.py', 'shallow_vs_deep_copy.py', 'inheritance_example.py', 'python_closure.py', 'super_test.py', 'utils', 'date_example.py', 'contextlib_example.py', 'test1.txt', 're_compile_vs_match.py', 'test.txt', 'iterator_example.py', 'str_repr_eval.py', 'generator_example.py','init_vs_call.py', 'main.py', 'filter_map_reduce.py', '_test_runner.py']
20

['timeit_test.py', 'args_kwargs.py', 'fibonacci.py', 'shallow_vs_deep_copy.py', 'inheritance_example.py', 'python_closure.py', 'super_test.py', 'utils', 'utils/__init__.py', 'utils/utils.py', 'utils/utils1', 'date_example.py', 'contextlib_example.py','test1.txt', 're_compile_vs_match.py', 'test.txt', 'iterator_example.py', 'str_repr_eval.py', 'generator_example.py', 'init_vs_call.py', 'main.py', 'filter_map_reduce.py', '_test_runner.py']
22
"""

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)