skip function if folder is empty - python-3.x

I want to read folder name(A/B/C/D) and call the convenable function for each file in Files folder and then process the next file (pass automatically to the next file and function).
Now i want to skip the function if the folder is empty how can i add this condition to my code please
Here is my code :
base_path = 'Files/'
for name in os.listdir(base_path):
path = os.path.join(base_path, name)
if os.path.isdir(path):
files = [os.path.join(path, f) for f in os.listdir(path)]
if name_to_func[path].__code__.co_argcount == len(files):
name_to_func[path](*files)
else:
name_to_func[path](files)
else:
name_to_func[path](path)

You can check like this if a directory is empty:
if len(os.listdir(path)) == 0:
# Directory is empty
else:
# Directory is not empty

Related

List is empty when appending when using recursion

I have two functions. The first one is used to get a list of paths to text files, and the second one is used to iterate over this list of paths and then check if they include the word password. But because of the Try Except statement in the second function, I had to use recursion to make it continue running unless there's another way if possible to provide below. My problem is that the list returned in the second function is empty why and how to fix it?
def search_txt():
"""Function to search the C:\\ for .txt files -> then add them (including full path to file) to a list."""
list_of_txt = []
for dir_path, sub_dir, files in os.walk("C:\\"):
"""Method 1 -> checks the end of the file name (could be used for specific extensions)"""
for file in files:
if file.endswith(".txt"):
list_of_txt.append(os.path.join(dir_path, file))
return list_of_txt
def search_pass_file(list_of_files: list):
"""Function to iterate over each text file, searching if the word "password" is included -> Returns the text
file's path """
list_of_pass = []
if len(list_of_files) != 0:
for i in range(len(list_of_files)):
file = list_of_files.pop()
try:
with open(file, encoding="utf8") as f:
for line in f.readlines():
if "password" in line:
list_of_pass.append(file)
except UnicodeDecodeError:
return search_pass_file(list_of_files)
except PermissionError:
return search_pass_file(list_of_files)
else:
return list_of_pass
if __name__ == '__main__':
myList = search_txt()
print(search_pass_file(myList))
You're returning list_of_pass only if len(list_of_files) == 0 (it's in the else block). Your return statement should occur after the loop (which should be a while one btw)
You can except several errors in one line by putting them in parenthesis: except (UnicodeDecodeError, PermissionError) of except all exceptions (for instance, you're not handling FileNotFoundError).
I'd reduce your function to:
def search_pass_file(list_of_files: list):
"""Function to iterate over each text file, searching if the word "password" is included -> Returns the text
file's path """
list_of_pass = []
while list_of_files:
file = list_of_files.pop()
try:
with open(file, encoding="utf8") as f:
for line in f.readlines():
if "password" in line:
list_of_pass.append(file)
break
except Exception:
list_of_pass += search_pass_file(list_of_files)
return list_of_pass
Edit: also in your except block, you should append the returned value of the recursive function to list_of_pass otherwise you'll lose the files found after the error occurs.

Want to create a csv inside a folder if it does not exist using string parameter in python

dirLocation = "Patients Data/PatientsTimelineLog.csv"
try:
if os.path.isfile(dirLocation):
print("Directory exist." + dirLocation)
else:
print("Directory does not exists. Creating new one." + dirLocation)
os.makedirs(os.path.dirname(dirLocation))
except IOError:
print("Unable to read config file and load properties.")
Automatically creating directories with file output
Want to create a PatientsTimelineLog.csv inside Patients Data folder in one go if it does not exist. The above link is creating the folder but the csv file is not made. makedir is used to make directory but i want inside the file in it like the path given above in dirLocation.
Inside the else, you can directly use os.makedirs(dirLocation).
When you use os.path.dirname(dirLocation) you are selecting everything except the name of the csv file. That is why you are creating only the folder.
try:
folder_path = os.path.split(os.path.abspath(dirLocation))
sub_path = folder_path[0]
if os.path.isdir(sub_path):
print("Directory exist: " + dirLocation)
else:
print("Directory does not exists. Creating new one: " + dirLocation)
file_name = PurePath(dirLocation)
obj = file_name.name
filepath = os.path.join(sub_path, obj)
os.makedirs(sub_path)
f = open(filepath, "a")
except IOError:
print("Unable to read config file and load properties.")
This is the answer to my question. pathlib did lot of help in this question

Continues variable not triggering while loop

Apologies if this is a repost. I am trying to write a while loop with a continue variable and if/else statement. My issue is that my continue variable is being ignored I cannot find the problem thus far. So far I have moved the while continues == 'y' condition into the else block now I am a bit flummoxed on why this var is being overlooked.
code:
def add_to_existing_file(data):
# data[0]-api response
# data[1]-city
# infile-file object returned from openFile()
# file_name- file name string. check filetype & report version.
continues = 'y' # set up continue variable
while continues == 'y':
file_name = input("Enter File Path to file to be appended: ") # get file from user
if file_name is False:
print("Now Creating Excel File..") # create condition for no user response.
return # if empty response exit function
else:
infile = appends.openFile(file_name) # open file to work with. Returns file object.
added_data = appends.journal_report_1_to_df(infile, file_name, data[0], data[1]) # append selected file to existing df
continues = input("Do you want to append another file? Y or N").lower() # check if new file
return added_data # return new df w/appended data
The problem happens on the last line. You're returning at the end of the first iteration, which exits the loop. This can be fixed by moving the return to the outer scope.
def add_to_existing_file(data):
# data[0]-api response
# data[1]-city
# infile-file object returned from openFile()
# file_name- file name string. check filetype & report version.
continues = 'y' # set up continue variable
while continues == 'y':
file_name = input("Enter File Path to file to be appended: ") # get file from user
if file_name is False:
print("Now Creating Excel File..") # create condition for no user response.
return # if empty response exit function
else:
infile = appends.openFile(file_name) # open file to work with. Returns file object.
added_data = appends.journal_report_1_to_df(infile, file_name, data[0], data[1]) # append selected file to existing df
continues = input("Do you want to append another file? Y or N").lower() # check if new file
return added_data # return new df w/appended data
It should work if you get the second return line (return added_data # return new df w/appended data) to have the same indentation as your while line. As a basic outline for a continue loop:
def function
continues = 'y'
while
if :
elif :
else :
print
continue ?
return

os.path.exists returns false but not raising exception in try/except block

I'm trying to validate a list of input directories and want the script to raise errors if the directories do not exist. I don't believe if-not will work here since if these folders do not exist (with the required input files [I have another validation for this]) then the script cannot run.
folder1 = "d:\\temp\\exists"
folder2 = "d:\\temp\\notexists"
list = [folder1, folder2]
list #gives ['d:\\temp\\exists', 'd:\\temp\\notexists']
for l in list:
try:
os.path.exists(l)
print("{0} folder exists...".format(l))
except FileNotFoundError:
print("{0} folder does not exist!".format(l))
os.path.exists correctly identifies folder2 as not existing, but does not raise an exception:
True
d:\temp\exists folder exists...
False
d:\temp\notexists folder exists...
If you want the code to stop and raise an error:
for l in list:
if os.path.exists(l):
print("{0} folder exists...".format(l))
else:
raise FileNotFoundError("{0} folder does not exist!".format(l))
if...else block should do the trick
folder1 = "d:\\temp\\exists"
folder2 = "d:\\temp\\notexists"
list = [folder1, folder2]
list #gives ['d:\\temp\\exists', 'd:\\temp\\notexists']
for l in list:
if os.path.exists(l)
print("{0} folder exists...".format(l))
else:
print("{0} folder does not exist!".format(l))

Check a folder if it contains anything python3

I need code that's able to check a folder in the same directory as the python script if it contains either folders or files
this code from How to check to see if a folder contains files using python 3 doesn't work
import os
for dirpath, dirnames, files in os.walk('.'):
if files:
print dirpath, 'Contains files or folders'
if not files:
print dirpath, 'Contains nothing'
The folder I'm checking is DeviceTest
Working
Try this code which uses OSError and aslo os.rmdir never directory which are not empty.So we can use this exception to solve the problem
import os
dir_name = "DeviceTest"
try:
os.rmdir(dir_name)
except OSError as exception_name:
if exception_name.errno == errno.ENOTEMPTY:
print("Directory contains files")
else:
print("Directory don't contain files and is empty")
Simple solution
import os
dir_name = "DeviceTest"
if os.listdir(dir_name) == []:
print("Empty")
for path, dirs, files in os.walk(folder):
if (files) or (dirs):
print("NOT EMPTY: " + str(path))
if (not files) and (not dirs):
print("EMPTY : " + str(path))

Resources