Renaming all the files in a folder is renaming the sub folders too - python-3.x

When try to rename the files in a specific folder, the program code renames
all the sub folders too. Is there a way to fix it?
dname = input("\nenter the path\t")
if os.path.isdir(dname):
dst = input("\nenter new file name: \t")
n = 1
for i in os.listdir(dname):
if not os.path.isdir(i):
mystr = ".txt"
src = os.path.join(dname, i)
dd = dst + str(n) + mystr
dd = os.path.join(dname, dd)
os.rename(src, dd)
n += 1

Yours "isdirectory" (os.path.isdir(i)) check doesn't seem to work.
You can precompile the list of files present in the directory using the below code,
files = (file for file in os.listdir (dname)
if os.path.isfile ( os.path.join ( dname, file) ))
And then directly iterate over the files, like,
for i in files:
mystr = ".txt"
src = os.path.join(dname, i)
dd = dst + str(n) + mystr
dd = os.path.join(dname, dd)
os.rename(src, dd)
n += 1
You can also have a look at this answer, which lists all the ways in which you can list files in a given directory.
Link: https://stackoverflow.com/a/14176179/10164003
Thanks

It seems below the line isn't working for you.
os.path.isdir(i)
Try out creating the full path before checking :
os.path.isdir(os.path.join(dname, i)):

Related

Re-naming multiple files

I have multiple directories inside which there are multiple files.
In directory1 files have the name format:
1.2.826.0.1.3680043.2.133.1.3.49.1.124.27456-3-1-10jd0au.dcm
1.2.826.0.1.3680043.2.133.1.3.49.1.124.27456-3-2-10jd0av.dcm
....
1.2.826.0.1.3680043.2.133.1.3.49.1.124.27456-3-10-17v7m18.dcm
In directory2:
1.2.826.0.1.3680043.2.133.1.3.49.1.46.34440-4-1-r3hu3u.dcm
1.2.826.0.1.3680043.2.133.1.3.49.1.46.34440-4-2-r3hu3v.dcm
....
and so on.
How can I rename these as just 1.dcm, 2.dcm,.....in each directory?
My attempt is as follows:
for dpath, dnames, fnames in os.walk(dir_path):
for dname in dnames:
directory = os.path.join(dir_path,dname)
for filename in os.listdir(directory):
old_name = os.path.join(directory,filename)
new = filename[filename.find("-"):]
new_name = os.path.join(directory, new)
os.rename(old_name, new_name)
But this only yields:
-3-1-10jd0au.dcm
-3-10-17v7m18.dcm
You could write a function that uses a regex to extract the parts of the filename that you need, for example:
import re
def ExtractNumber(filename):
parts = re.search(r".*-.*-(.*)-.*(\..*)", filename)
return parts.group(1) + parts.group(2)
print(ExtractNumber("1.2.826.0.1.3680043.2.133.1.3.49.1.124.27456-3-1-10jd0au.dcm"))
print(ExtractNumber("1.2.826.0.1.3680043.2.133.1.3.49.1.124.27456-3-10-17v7m18.dcm"))
Outputs:
1.dcm
10.dcm

Find folders that has no data in it and get their folder names

I want to find folders that has no data in it and get thier folder names.
The first and second folders are named randomly in numbers and has data in random folders.
the codes are
path = 'M://done/mesh/*'
FL = glob.glob(path)
FL2 = glob.glob(FL[0] + '/*')
FL2
['M://done/mesh\\41\\23',
'M://done/mesh\\41\\24',
'M://done/mesh\\41\\33',
'M://done/mesh\\41\\34',
'M://done/mesh\\41\\35',
'M://done/mesh\\41\\36',
'M://done/mesh\\41\\43',
'M://done/mesh\\41\\44',
'M://done/mesh\\41\\45',
'M://done/mesh\\41\\46',
'M://done/mesh\\41\\47',
'M://done/mesh\\41\\53',
'M://done/mesh\\41\\54',
'M://done/mesh\\41\\55',
'M://done/mesh\\41\\63',
'M://done/mesh\\41\\64',
'M://done/mesh\\41\\65',
'M://done/mesh\\41\\66',
'M://done/mesh\\41\\67',
'M://done/mesh\\41\\74',
'M://done/mesh\\41\\75',
'M://done/mesh\\41\\76',
'M://done/mesh\\41\\77',
'M://done/mesh\\41\\85',
'M://done/mesh\\41\\86',
'M://done/mesh\\41\\87']
FL2[24][24:26] + FL2[24][27:30] + '0000' # why do I need [24:26}, [27:30]???
finding_files = ['_Caminfo.dat','running.csv']
print(FL2[0] + '/0000/02_output/' + FL2[0][24:26] + FL2[0][27:30] + '0000/' + fn1[0])
'41860000'
You can use os.listdir to find empty folders, like below:
import os
folder_list = ["D:\\test_1", "D:\\test_2"]
empty_folders = []
for folder in folder_list:
try:
if not os.listdir(folder):
empty_folders.append(folder)
except FileNotFoundError:
pass
print(empty_folders)

Renaming, Moving, and Deleting Original Directory

I'm trying to right a script that will walk through a given directory and rename, move, and delete the original directory. Each directory has a *.mp4 file and a subfolder containing *.jpg files. I'm having trouble deleting the original directory when I'm done renaming and moving the files. What so far is:
import datetime, os, re, shutil, logging, smtplib
logging.basicConfig(level = logging.INFO, format = ' %(asctime)s - %(levelname)s - %(message)s')
#logging.disable(logging.info)
path = '\\\\RT-N66U\\sda2\\Documents'
desired_text1 = re.compile(r'^\d{3}_[a-zA-Z]+\d{3}.jpg')
desired_text2 = re.compile(r'^\d{3}_[a-zA-Z]+_\d{3}.jpg')
renamed_files = ''
for folderName, subfolders, filenames in os.walk(path):
if folderName.startswith(path + '\\GEO-'):
logging.info('The current folder is ' + folderName)
for subfolder in subfolders:
if subfolder.startswith('Pics'):
pic_folder = subfolder
for filename in filenames:
if filename.endswith('.mp4'):
changed_date = datetime.datetime.strptime(filename[3:17], '%b %d, %Y').strftime('%y.%m.%d') # Changes the name of the date to the desired format
year = datetime.datetime.strptime(filename[3:17], '%b %d, %Y').strftime('%Y')
name = filename[20:-25]
name = name.lower()
modified_name = '.'.join(re.findall('\S+', name))
final_name = 'geo.' + changed_date + '.' + modified_name
if not os.path.exists('\\\\RT-N66U\\sda2\\Me\\GEO\\%s\\%s\\%s' % (year, changed_date[3:5], final_name)):
os.makedirs('\\\\RT-N66U\\sda2\\Me\\GEO\\%s\\%s\\%s' % (year, changed_date[3:5], final_name))
if not os.path.exists('\\\\RT-N66U\\sda2\\Me\\GEO\\%s\\%s\\%s\\%s' % (year, changed_date[3:5], final_name, pic_folder)):
os.makedirs('\\\\RT-N66U\\sda2\\Me\\GEO\\%s\\%s\\%s\\%s' % (year, changed_date[3:5], final_name, pic_folder))
if filename.endswith('.mp4'):
logging.info(filename)
os.rename(folderName + '\\' + filename, '\\\\RT-N66U\\sda2\\Me\\GEO\\%s\\%s\\%s\\%s.mp4' % (year, changed_date[3:5], final_name, final_name))
# This part will logg and rename the files by adding a '_'
mo1 = desired_text1.search(filename)
mo2 = desired_text2.search(filename)
if mo1:
logging.info(folderName + '\\' + filename)
os.rename(folderName + '\\' + filename, '\\\\RT-N66U\\sda2\\Me\\GEO\\%s\\%s\\%s\\%s\\%s_%s' % (year, changed_date[3:5], final_name, pic_folder, filename[:-7], filename[-7:]))
renamed_files += filename + ' -> ' + filename[:-7] + '_' + filename[-7:] + '\n'
elif mo2:
logging.info(folderName + '\\' + filename)
os.rename(folderName + '\\' + filename, '\\\\RT-N66U\\sda2\\Me\\GEO\\%s\\%s\\%s\\%s\\%s' % (year, changed_date[3:5], final_name, pic_folder, filename))
renamed_files += filename + '\n'
# This part will check if the directory is empty and delete it if so
if os.listdir(folderName) == []:
logging.info(folderName)
shutil.rmtree(folderName)
What ends up happening is that all sub-directories will be deleted if they're empty and leaving the primary directory empty. I would like the primary directory to be removed as well, since all the files have been moved. Is there a way to accomplish this within the for statement?
If you mean deleting the directory known as folderName inside your main for loop, I think it's not really possible since you're iterating over an object that contains it. Like if inside a for i in this_list: you would like to remove an object from this_list. This is not possible before you're out of the loop.
In order to achieve what you want, I would write a function to recurse into the folder tree. The idea would be something like:
def process_folder(folder_name):
do some stuff on files
get the subfolders of folder_name
for f in subfolders:
process_folder(subfolder_name)
if subfolder_name is empty, delete it
maybe do some other stuff on files
and in the main script, call process_folder(path). (This would leave only the top folder there even if it's empty though, so be sure you don't want to delete it; or to call process_folder at a higher level, or to add an instruction to delete it too if it's empty).

write excel file to many folders in directory using matlab

I need to write an excel file to many folders ( folder* ) under D:\ and loop over them to further process individually.
i tried the following code for long time ..
srcFolders = dir('D:\folder*');
for i = 1 : length(srcFiles)
filename = strcat(path,'\',srcFiles(i).name);
xlswrite('srcFolders\filename.xls', srcFolders(folder).name,'Sheet1', folder_range);
end
I'm assuming that you want to write different sets of data to a Excel file and were just having some trouble. If that's not accurate comment and let me know.
%Just generating some arbitrary data
data = arrayfun(#(m,n) rand(m,n), randi(50, 9, 1), randi(50, 9, 1), 'uni', 0);
%The base file path
path = 'D:';
%The pattern used to choose the folders
folderPattern = 'folder*';
%The files you want to write to
srcFiles = {'A', 'B', 'D'};
%And the extension
ext = '.xlsx';
%Get the path of the folders
srcFolders = dir(fullfile(path, folderPattern));
srcFolders = fullfile(path, {srcFolders.name});
%Construct the full file path
fullPath = cellfun(#(f) fullfile(f, strcat(srcFiles(:), ext)), srcFolders, 'uni', 0);
fullPath = vertcat(fullPath{:});
%Write the data to the files
for i = 1:length(fullPath)
xlswrite(fullPath{i}, data{i})
end
Edit:
Based on OP's feed.
Note for the second overhaul. I didn't test this and I'm done. This was way to much for a single question and you are abusing the way this website is supposed to work.
%The base file path
path = 'D:';
%Relative reference to reference images
ImageRefLocations = {'Ref\RefI1.jpg', 'Ref\RefI2.png', 'Ref\RefI3.jpg'};
%Base Image location
baseImage = fullfile(path, ImageRefLocations(:));
%The pattern used to choose the folders
folderPattern = 'folder*';
%The image extension
[~, ~, ext] = unique(cellfun(#(f) fileparts(f), baseImage, 'uni', 0));
%The excel extension
ExcelExt = '.xlsx';
msg = {' = no'; ' = ok'};
i0 = cellfun(#(f) imread(f), baseImage, 'uni', 0);
%Get the path of the folders
srcFolders = dir(fullfile(path, folderPattern));
isDir = [srcFolders.isdir];
srcFolders = {srcFolders(isDir).name}';
PathedFolders = fullfile(path, srcFolders);
excelFiles = fullfile(path, strcat(srcFolders, ExcelExt));
for i = 1:length(PathedFolders)
f = PathedFolders{i};
Images = cellfun(#(x) dir(fullfile(f, ['*', x])), ext, 'uni', 0);
Images = vertcat(Images{:});
if isempty(Images)
continue
end
Images = {Images.name}';
[~, ImageNames, ~] = cellfun(#(x) fileparts(x), Images, 'uni', 0);
ImageList = fullfile(f, Images);
match = zeros(size(ImageList));
for j = 1:length(ImageList)
image = imread(ImageList{j});
for k = 1:length(i0)
if ~all(size(image) == size(i0{k}))
continue
end
match(j) = all(image(:) == i0{k}(:));
if match(j)
continue
end
end
end
matchMessage = strcat(Images, msg(match + 1));
xlswrite(excelFiles{i}, matchMessage)
end

Script to rename and copy files to a new directory.

Hi I have recently made this script to rename files I scan for work with a prefix and a date. It works pretty well however it would be great if it could make a directory in the current directory with the same name as the first file then move all the scanned files there. E.g. First file is renamed to 'Scanned As At 22-03-2012 0' then a directory called 'Scanned As At 22-03-2012 0' (Path being M:\Claire\Scanned As At 22-03-2012 0) is made and that file is placed in there.
I'm having a hard time figuring out the best way to do this. Thanks in advance!
import os
import datetime
#target = input( 'Enter full directory path: ')
#prefix = input( 'Enter prefix: ')
target = 'M://Claire//'
prefix = 'Scanned As At '
os.chdir(target)
allfiles = os.listdir(target)
count = 0
for filename in allfiles:
t = os.path.getmtime(filename)
v = datetime.datetime.fromtimestamp(t)
x = v.strftime( ' %d-%m-%Y')
os.rename(filename, prefix + x + " "+str(count) +".pdf")
count +=1
Not quite clear about your requirement. If not rename the file, only put it under the directory, then you can use the following codes (only the for-loop of your example):
for filename in allfiles:
if not os.isfile(filename): continue
t = os.path.getmtime(filename)
v = datetime.datetime.fromtimestamp(t)
x = v.strftime( ' %d-%m-%Y')
dirname = prefix + x + " " + str(count)
target = os.path.join(dirname, filename)
os.renames(filename, target)
count +=1
You can check help(os.renames).

Resources