Check a folder if it contains anything python3 - python-3.x

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

Related

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

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

How to save files to a directory and append those files to a list in Python?

Scenario:
I want to check whether if a directory contains a certain '.png' image file. If so, this image file along with all the other files (with png extension only) gets stored in a different directory. (The solution I am looking for should work in all OS platforms i.e Windows, Unix, etc.) and in a remote server i.e (FTP etc.)
I have tried the following code below:
import os, sys
import shutil
import pathlib
import glob
def search():
image_file = 'picture.png'
try:
arr = [] #List will be used to append all the files in a particular directory.
directory = pathlib.Path("collection") #checks if the collection directory exists.
files = []
#need to convert the PosixPath (directory) to a string.
[files.extend(glob.glob(str(directory) + "/**/*.png", recursive = True))]
res = [img for img in files if(img in image_file)] #checks if the image is within the list of files i.e 'picture.png' == 'collection\\picture.png'
if str(bool(res)): #If True...proceed
print("Image is available in image upload storage directory")
for file in files:
transfer_file = str(file)
shutil.copy(file, 'PNG_files/') #send all the files to a different directory i.e 'PNG_files' by using the shutil module.
arr.append(transfer_file)
return arr
else:
print("image not found in directory")
except OSError as e:
return e.errno
result = search() #result should return the 'arr' list. This list should contain png images only.
However, during execution, the For loop is not getting executed. Which means:
The image files are not stored in the 'PNG_files' directory.
The images are not getting appended in the 'arr' list.
The code above the For loop worked as expected. Can anyone explain to me what went wrong?
There are several issues:
In this line
res = [img for img in files if(img in image_file)] #checks if the image is within the list of files i.e 'picture.png' == 'collection\\picture.png'
you should check the other way around (as written in the comment): image_file in img, e.g. picture.png in collection/picture.png.
str(directory) + "/**/*.png" is not OS independent. If you need this to work on Windows, too, you should use os.path.join(str(directory), '**', '*.png') instead!
This check is incorrect: if str(bool(res)):. It's actually always true, because bool(res) is either True or False, str(bool(res)) is either "True" or "False", but both are actually True, as neither is an empty string. Correctly: if res:.
And finally, you're missing the creation of the PNG_files directory. You need to either manually create it before running the script, or call os.mkdir().

How to choose & save files to a directory with Python 3?

I'm having trouble making a subfolder for files to be stored into after choosing the Parent Folder or directory.
This is my current script:
import os, sys, subprocess, shutil, glob, os.path, csv
#User Chooses Folder or File Path Directory
path_new = filedialog.askdirectory()
def saveData():
serial_number = input('Scan Barcode: ')
folder_name = print('Folder Name:', serial_number)
os.chdir(path_new) #Not sure if this is necessary
if not os.path.exists(path_new):
os.makedirs(path_new)
print ('The data has been stored in the following directory:', path_new)
shutil.move('file_directory/TOTAL.csv', 'chosen_directory/%s'% (serial_number))
shutil.move('file_directory/enviro.csv', 'chosen_directory/%s' % (serial_number))
The script runs, but just not how I would like it to. Does anyone have any recommendations or an alternate solution to creating a folder and selecting it as the directory to have subfolders created and have files transferred into them?
I resolved my issue. If anyone else knows of a "cleaner" way of writing this out please update with a better answer. As of now this does exactly what I want.
Code:
import os, sys, shutil. os.path
path = filedialog.askdirectory()
def saveData():
serial_number = input('Scan Barcode: ')
folder_name = print('Folder Name:', serial_number)
path_new = os.path.join(path, '%s' % (serial_number))
if not os.path.exists(path_new):
os.makedirs(path_new)
shutil.move('C:/files/TOTAL.csv', path_new)
shutil.move('C:/files/enviro.csv', path_new)
print('The data has been stored in the following directory:', path_new)

Shutil ignore_patterns not doing anything

I have a script that copies files from a folder to another folder, but I want it to ignore the txt files. I have this code that works, but it does not ignore the txt files. It just copies everything without any warning.
What am I doing wrong?
import sys, os, shutil
script, filetobackup = sys.argv
backupdir = r'*path to backupdir*'
def copytree(filetobackup, backupdir, symlinks=False):
if not os.path.exists(backupdir):
os.makedirs(backupdir)
for item in os.listdir(filetobackup):
s = os.path.join(filetobackup, item)
d = os.path.join(backupdir, item)
if os.path.isdir(s):
shutil.copytree(s, d, symlinks, ignore=ignore_patterns('*.txt'))
else:
if not os.path.exists(d) or os.stat(s).st_mtime - os.stat(d).st_mtime > 1:
shutil.copy2(s, d)
copytree(filetobackup, backupdir)
Edit: Hmm, no one knows?

Resources