How to select specific filenames nested within several folders? - python

I have a working folder on "C:\Users\userName\Desktop\test" where my python test script is located. My idea was to import directory from another drive ("D:\mydir\mytests\Projects") to my current working directory:
import os
from os import getcwd
curdir=os.getcwd()
path = os.chdir(os.path.join(curdir,"D:\mydir\mytests\Projects"))
Under "Projects" directory there are several folders which my contain also subfolders (but not every). I am trieng to make some kind of a generic code that will iterate over "Projects" directory access every folder or subfolder if it exist and find specific files with ".proj" extension. Found files (".proj") should than be writen out in a form of a list (maybe) so i can run each of them one by one with a for loop. I tried to write down some code but not successfully. Any suggestion will be appreciated a lot.
proj_list = []
for dirpath, dirnames, files in os.walk(path):
for f in files:
dest_dir = glob.glob('*.proj')
fullpath = os.path.join(dirpath, f.dest_dir)
proj_list.append(fullpath)
def activate_approval(dialog):
dialog.activate_button('yes')
class OpenAllProjectsFromListAndRun(script.TestScript):
def test_run (self):
for project in fullpath:
with self.handle_dialog(activate_yes):
self.open_project(project)
'''nothing in particular'''
if __name__ == '__main__':
test = OpenAllProjectsFromListAndRun()
test.run()
PS: I'm using Python 2.7

Related

Find a file 1 folder level down

I am trying to get full_path of places.sqlite file present in '%APPDATA%\Mozilla\Firefox\Profiles\<random_folder>\places.sqlite' using Python OS module. The issue as you can see that <random_folder> has a random name and there could be multiple folders inside the Profiles folder.
How do I navigate/find the path to the places.sqlite file?
You would ideally want to go through each folder to search for this file. In terminal 'locate file_name' command would do this for you. In python file you can use the following command:
import os
db_path = os.path.join(os.getenv('APPDATA'), r'Mozilla\Firefox\Profiles')
def find_file(file_name, path):
for root_folder, directory, file_names in os.walk(path):
if file_name in file_names:
return os.path.join(root_folder, file_name)
print(find_file('places.sqlite', db_path))
os.walk gives a list of all files in a path recusivly. Use it to search for 'places.sqlite' as follows.
path = ""
for root, dirs, files in os.walk("%APPDATA%\\Mozilla\\Firefox\\Profiles\\"):
if "places.sqlite" in files:
path = os.path.join(root, 'places.sqlite')
break
Use the os module to list out all directories in %APPDATA%\Mozilla\Firefox\Profiles\
loop over the directories until you find places.sqlite file (also using os module)
A glob might be simpler as in this case one expects the file to be there in level below the Profiles folder or not there at all.
import os
import pathlib
profiles = pathlib.Path(os.environ["APPDATA"]) / "Mozilla" / "Firefox" / "Profiles"
# rglob will recursively search as well
if places := list(profiles.rglob("places.sqlite")):
print(places[0]) # will print the sqllite file path
with places[0].open() as f:
# ....

How to run a python script trough a folder with subfolders?

I am ripping dvd's to my plex server, and the way i have done it is like this.
\Storage
\Movie Name (xxxx)
Movie.mkv
Bonus Scene.mkv
\Movie2 Name (xxxx)
Movie2.mkv
etc
And what i want to do with my python script is to rename each MKV file to the folder name. But instead of running the script in each folder, how do i run it across the main storage folder and make it enter each subfolder?
My script looks like this (the script requires the movie title to be 1.mkv, i made it like that so it leaves the bonus scenes alone)
import os
folder = "{cwd}\\".format(cwd = os.getcwd())
src = "{folder}".format(folder=folder)
extension = "mkv"
def renamer():
path = os.path.dirname(src)
folder = os.path.basename(path)
os.rename("{directory}\\{file}".format(directory=src, file="1.mkv"),
"{directory}\\{file}.{extension}".format(directory=src, file=folder, extension = extension))
def listDir():
for file in os.listdir(src):
if file.endswith(".{extension}".format(extension = extension)):
return file
def main():
renamer()
if __name__ == "__main__":
main()
you can use:
for (dirpath, dirnames, filenames) in os.walk(your_initial_directory):
from there you get 3 lists dirpath, dirnames, filenames that are in your_initial_directory

my program of searching file does not search folder inside folder

I have made a file search program which search for the file. it is working fine with searching in current working directory and also inside one folder, however it does not work folder inside folder, I am not getting why? Can anyone please help?
My Code:
import os
files = []
def file_search(file, path=""):
if path == "":
path = os.getcwd()
for item in os.listdir(path):
if os.path.isdir(item):
path = os.path.realpath(item)
file_search(file, path)
elif item == file:
files.append(item)
return files
print(file_search("cool.txt"))
I think it will be simpler if you used glob library.
Example:
import glob
files = glob.glob('**/cool.txt', recursive=True)

Python: How to move list of folders (with subfolders) to a new directory

I have a directory that literally has 3000+ folders (all with subfolders).
What I need to be able to do is to look through the directory for those files and move them to another folder. I've done some research and I see that shutil is used to move files, but i'm unsure how to input a list of files to look for.
For example, in the directory, I would like to take the following folders (and their subfolders) and move them to another folder called "Merge 1"
1442735516927
1442209637226
1474723762231
1442735556057
1474723762187
1474723762286
1474723762255
1474723762426
1474723762379
1474723762805
1474723762781
1474723762936
1474723762911
1474723762072
1474723762163
1474723762112
1442209642695
1474723759389
1442735566966
I'm not sure where to start with this so any help is greatly appreciated. Thanks!
Combining os and shutil, following code should answer your specific question:
import shutil
import os
cur_dir = os.getcwd() # current dir path
L = ['1442735516927', '1442209637226', '1474723762231', '1442735556057',
'1474723762187', '1474723762286', '1474723762255', '1474723762426',
'1474723762379', '1474723762805', '1474723762781', '1474723762936',
'1474723762911', '1474723762072', '1474723762163', '1474723762112',
'1442209642695', '1474723759389', '1442735566966']
list_dir = os.listdir(cur_dir)
dest = os.path.join(cur_dir,'/path/leadingto/merge_1')
for sub_dir in list_dir:
if sub_dir in L:
dir_to_move = os.path.join(cur_dir, sub_dir)
shutil.move(dir_to_move, dest)

os.listdir() shows nothing while it is not so

I am trying to sort my files for school automatically but when I try this:
import os, sys
path = "/Sorting for School/"
dirs = os.listdir(path)
#print all dirs
for file in dirs:
print file
Although there are two txt documents in dir but when I run this the output is:
[]
Thanks
The code is fine. You must be querying a wrong path.
/dir/ means a subdirectory named dir in the root directory (in UNIX) or in the root directory of the current drive (in Windows).
Your code is fine. The following should work too:
import os
path = "/Sorting for School/"
def handle_err(err):
print err
for root,dirs,files in os.walk(path,onerror=handle_err):
for name in files:
print(name)

Categories