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)
Related
im creating script in python that get all files on disk, but no folders only files. Its my code.
import hashlib
import os
if os.name != "nt":
print("Sorry this script works only on Windows!")
path = "C://"
dir_list = os.listdir(path)
print(dir_list)
You can use for example the pathlib library and build something like that:
import pathlib
path = "" # add your path here don't forget a \ at the end on windows
for i in os.listdir(path):
if pathlib.Path(path + i).is_dir() is not True:
print(i)
It iterates through the current directory and checks if its a directory, by creating a Path object from the list entry and then checks on that object if it is a directory.
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:
# ....
I am trying to write a python program that takes an input directory, and prints out all the .txt files that are in the directory. However, if there is another folder inside that one, it must do the same thing using recursion.
My problem is that is only does the .txt files and does not traverse further into the directory.
import os
path = input("What directory would you like to search?: ")
def traverse(path):
files = os.listdir(path)
for i in files:
if os.path.isdir(i) == True:
traverse(i)
elif i.endswith('.txt'):
print(i)
traverse(path)
What is the problem?
It looks like the reason your code is failing is because the if os.path.isdir(i) == True line always fails, regardless of whether or not the file is the directory. This is because the files variable stores relative paths rather than absolute paths, which causes the check to fail.
If you want to do it using the recursion method you gave, your code can be changed as follows:
import os
path = input("What directory would you like to search?: ")
def traverse(path):
files = os.listdir(path)
files = (os.path.join(os.path.abspath(path), file) for file in files)
for i in files:
if os.path.isdir(i) == True:
traverse(i)
elif i.endswith('.txt'):
print(i)
traverse(path)
Here is a better way to do it using fnmatch (adapted to suit the rest of your code from Use a Glob() to find files recursively in Python?). It will recursively search all files in the supplied directory, and match those that end with
import fnmatch
import os
path = input("What directory would you like to search?: ")
def traverse(path):
matches = []
for root, dirnames, filenames in os.walk(path):
for filename in fnmatch.filter(filenames, '*.txt'):
matches.append(os.path.join(root, filename))
print matches
traverse(path)
You are missing full path otherwise it's fine. see below
def traverse(path):
files = os.listdir(path)
for i in files:
if os.path.isdir(os.path.join(path,i)):
traverse(os.path.join(path,i))
elif i.endswith('.txt'):
print(os.path.join(path,i))
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
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)