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)
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('----------------------')
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