Python name of latest folder created in a directory - python

I am new to python and have to play with directories.
Can someone help me with it?
I have to know a path with newly created folder. A new temp folder is generated by my code in which some files are copied. I have to know the path of this folder , but folder name is random , so I want to fetch the folder name of latest created folder.
What shall i do?

You can do something like this:
import os
directory = '.' # current dir
folders = os.walk(directory).next()[1]
creation_times = [(folder, os.path.getctime(folder)) for folder in folders]
creation_times.sort(key=lambda x: x[1]) # sort by creation time
Then you can pick the last element of this list:
most_recent = creation_times[-1][0]

Its a bad practice to fetch the latest folder created because some other application may create a folder right before you fetch the latest folder, but if you really want to try it out the code what elyase has demonstrated is fine.

Related

How do I copy subfolders into another location

I'm making a program to back up files and folders to a destination.
The problem I'm currently facing is if I have a folder inside a folder and so on, with files in between them, I can't Sync them at the destination.
e.g.:
The source contains folder 1 and file 2. Folder 1 contains folder 2, folder 2 contains folder 3 and files etc...
The backup only contains folder 1 and file 2.
If the backup doesn't exist I simply use: shutil.copytree(path, path_backup), but in the case, I need to sync I can't get the files and folders or at least I'm not seeing a way to do it. I have walked the directory with for path, dir, files in os.walk(directory) and even used what someone suggest in another post:
def walk_folder(target_path, path_backup):
for files in os.scandir(target_path):
if os.path.isfile(files):
file_name = os.path.abspath(files)
print(file_name)
os.makedirs(path_backup)
elif os.path.isdir(files):
walk_folder(files, path_backup)
Is there a way to make the directories in the backup folder from the ground up and then add the info alongside or is the only way to just delete the whole folder and use shutil.copytree(path, path_backup).
With makedirs, all it does is say it can't create because the folder already exists, this is understandable as it's trying to write in the Source folder and not in the backup. Is there a way to make the path to replace Source for backup?
If any more code is needed feel free to ask!

Creating ZIP folder with shutil - Python

I'm trying to use shutil.make_archive but it's duplicating the folder name. Let me explain better:
My folder R360 to be ziped is located at: C:\Users\PycharmProjects\Project\media\SAE\R360\
What I am trying to do is: create a zip folder with this same name. So in the SAE directory, it should be the regular folder R360 and then R360.zip.
My code:
folder = C:\Users\PycharmProjects\Project\media\SAE\R360
mediaFolder = C:\Users\PycharmProjects\Project\media\
shutil.make_archive(f'{folder}', 'zip', f"{mediaFolder}SAE/", f"{folder.split('/')[-1]}/")
The R360.zip is being created normally but the problem is that the zip folder is like this:
C:\Users\PycharmProjects\Project\media\SAE\R360.zip\R360\...
What I really wanted:
C:\Users\PycharmProjects\Project\media\SAE\R360.zip\...
It shouldn't be that R360 inside the zip folder.
I'd like to post my own question for other who are facing the same issue!
folder = C:\Users\PycharmProjects\Project\media\SAE\R360
mediaFolder = C:\Users\PycharmProjects\Project\media\
shutil.make_archive(f'{folder}/', 'zip', f"{mediaFolder}SAE/{folder.split('/')[-1]}")
This will create the zip file, without duplicating the folder itself inside the zip!

Read subfolder python

Im trying to make a data parser but using python for my project but each files are inside a separate folders to each other. Currently i am able to read the first folder but i havent figured out how to read the folder after that and put it in a for loop
import os
r_path='//esw-fs01/esw_niagara_no_bck/BuildResults/master/0.1.52.68_390534/installation_area/autotestlogs_top/'
sd_path='/.'
root = os.listdir(r_path)
subdir=os.listdir(sd_path)
for entry in root:
# print(entry)
if os.path.isdir(os.path.join(r_path, entry)):
for subentry in subdir:
if os.path.isdir(os.path.join(r_path,'/ConfigurationsTest_19469')):
print(subentry)
For the second for loop, i want to iterate every folder that are in autotestlogs folder. i tried to make it but it doesnt work apparently. Please help Thanks
I think you messed your order up a little bit. If you do subdir = os.listdir(sd_path) before the loop you can't possibly get the sub directories because you need to use the parent directory to get to them.
So in your loop after you checked that an "entry" is a folder you can store the absolute path of this folder in a variable and then list it's contents with os.listdir().
Then you can loop through those and parse them.
How I would do it:
import os
r_path='//esw-fs01/esw_niagara_no_bck/BuildResults/master/0.1.52.68_390534/installation_area/autotestlogs_top/'
root = os.listdir(r_path)
for entry in root:
# print(entry)
subdir_path = os.path.join(r_path, entry) # create the absolute path of the subdir
if os.path.isdir(subdir_path): # check if it is a folder
subdir_entries = os.listdir(subdir_path) # get the content of the subdir
for subentry in subdir_entries:
subentry_path = os.path.join(subdir_path, subentry) # absolute path of the subentry
# here you can check everything you want for example if the subentry has a specific name etc
print(subentry_path)

Get directory after specific folder name in Python

I am trying to get the rest of the directory after a specific folder. Say, for example:
/heres/some/folders/with/files
And I want everything after /folders/:
/with/files
This is what I have:
Tk().withdraw()
directory = os.path.basename(filedialog.askdirectory())
print(directory)
I know that basename only prints the current folder, but I could not find anything on this to even try and code it.

Renaming multiple sub folders to match the parent folder's name

I'm a python beginner but have some basic experience, and I need someone to please help me use the os module to rename sub folders based on their parent folder. I've been searching for answers for the past week and have not had any success. I'm assuming I need to use the os.walk method to do this.
Here is my folder structure:
C:\data\test\
C:\data\test\map1
C:\data\test\map1\1617151
C:\data\test\map2
C:\data\test\map2\181719
C:\data\test\map3
C:\data\test\map3\182726
C:\data\test\map4
C:\data\test\map4\894932
I need the results to look like this.
C:\data\test\
C:\data\test\map1
C:\data\test\map1\map1
C:\data\test\map2
C:\data\test\map2\map2
C:\data\test\map3
C:\data\test\map3\map3
C:\data\test\map4
C:\data\test\map4\map4
Can someone please help?
python 2.7:
import os
os.chdir("C:\data\test\") # go to dir
sub_dirs = os.walk('.').next()[1] # get list of subdirs
for sub_dir in sub_dirs:
sub_sub_dir = os.walk('.').next[1] # get sub-subdir
os.rmdir(sub_sub_dir) # remove sub-subdir
os.makedirs(sub_dir + '\bla') # make new sub-subdir named subdir\bla
python 3+:
import os
os.chdir("C:\data\test\")
sub_dirs=next(os.walk('.'))[1]
for sub_dir in sub_dirs:
sub_sub_dir = next(os.walk('.'))[1]
os.rmdir(sub_sub_dir)
os.makedirs(sub_dir + '\bla')
Untested, but should do it.
You can get a list of all the files and it's respective folder location using this one liner:
here = '.' # Current location
files = [(root, files) for root, dirs, files in os.walk(here) if (not dirs and files)]
For the given folder structure it will return:
[
('C:\data\test\map1', ['1617151']),
...
]
You can now loop over this list and rename the files (https://docs.python.org/3/library/os.html#os.rename). You can get the parent folder's name by splitting the root string (root.split('\')[-1]).

Categories