Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinguishing between files and directories in Python

Tags:

I am trying to get only files in the folder excluding any other directories. but the below script is moving all the files and folders to another directory.

while True:
    # Go through each of the directories
    for mylist in dirlist:
        check_dir = mylist[0]
        callback = mylist[1]

        # get the list of files in the directory
        filelist = os.listdir(check_dir)
        for this_file in filelist:
            if ((this_file == ".") or (this_file == "..") or (this_file == "donecsvfiles") or (this_file == "doneringofiles")):
                print "Skipping self and parent"
                continue

            full_filename = "%s/%s"%(check_dir, this_file)
like image 712
preethi Avatar asked Jan 29 '18 17:01

preethi


1 Answers

In os.path, there are helpful isdir() and isfile() functions:

>>> import os
>>> 
>>> os.path.isfile('demo.py')
True
>>> os.path.isdir('demo.py')
False
>>> os.path.isfile('__pycache__')
False
>>> os.path.isdir('__pycache__')

Also, you can use os.walk() or os.scandir() to automatically separate the two:

for root, dirs, files in os.walk('python/Lib/email'):
    print('Searching:', root)
    print('All directories', dirs)
    print('All files:', files)
    print('----------------------')
like image 182
Raymond Hettinger Avatar answered Sep 20 '22 12:09

Raymond Hettinger