I have the below code to print the filename which is find criteria with file extension *.org. How could I print the relative path of the file found. Thanks in advance
def get_filelist() :
directory = "\\\\networkpath\\123\\abc\\"
filelist = []
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith('Org'):
print(str(dirs) +"\\" + str(file)) #prints empty list [] followed by filename
filelist.append(os.path.splitext(file)[0])
return (filelist)
Please see me as novice in python
files and dirs list the children of root. dirs thus lists siblings of file. You want to print this instead:
print(os.path.relpath(os.path.join(root, file)))
you need to use os.path.join:
def get_filelist() :
directory = "\\\\networkpath\\123\\abc\\"
filelist = []
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith('org'): # here 'org' will be in small letter
print(os.path.join(root,file))
filelist.append(os.path.join(root,file))
return filelist
Related
I would like to know how I can only append sub-directories of a given directory to a list in Python.
Something like this is not what I'm searching for as it outputs the files:
filelist = []
for root, dirs, files in os.walk(job['config']['output_dir']):
for file in files:
# append the file name to the list
filelist.append(os.path.join(root, file))
# print all the file names
for name in filelist:
print(name)
Just use the dirs variable instead the files variable, like this:
dirs_list = []
for root, dirs, files in os.walk('test'):
for dir in dirs:
dirs_list.append(os.path.join(root, dir))
print(dirs_list)
I am trying to recursively list all file names that are in sub directories called Oracle (but not list files in other sub directories).
I have the following code:
for root, dirs, files in os.walk(r"Y:\Data\MXD_DC\DataSourceChange", topdown=True):
for name in dirs:
if fnmatch.fnmatch(name, 'Oracle'):
for filename in files:
fullpath = os.path.join(root, filename)
print "FullPath is: " + fullpath
I can only get it to list all file names of all sub directories. It does not even go to the sub directory called Oracle.
Currently, when you find a directory named Oracle, you list the files that are at the same level in the hierachy instead of listing the files contained in the Oracle folder, because the tuple returned by os.walk contains directories and files at same level.
You have 2 ways to list the expected files:
only use dirnames from walk and use listdir once you have found an Oracle folder
for root, dirs, files in os.walk(r"Y:\Data\MXD_DC\DataSourceChange", topdown=True):
for name in dirs:
if name == 'Oracle':
path = os.path.join(root, name)
for filename in os.listdir(path):
fullpath = os.path.join(path, filename)
print "FullPath is: " + fullpath
ignore dirnames, use last component from root and test if it is Oracle:
for root, dirs, files in os.walk(r"Y:\Data\MXD_DC\DataSourceChange", topdown=True):
if os.path.basename(root) == 'Oracle':
for filename in files:
fullpath = os.path.join(root, filename)
print "FullPath is: " + fullpath
if you want to list the files in a particular directory you can use
import os
os.listdir("Oracle")
to print the directories from a script use this
import os
print "%s" %os.listdir("Oracle")
Given a list of file names, I want to create the full path for these files if they exist in a given directory or it's sub-directories. Right now I use this code
def construct_path(file_list, directory):
file_path_list = []
for name in file_list:
for dir, subdir, filenames in os.walk(directory):
if name in filenames:
file_path_list.append(os.path.join(dir, name))
return file_path_list
So here the directory is being crawled for each file in the list. Is there a faster/better way to do it?
You can remove the loop over the file_list and remove found files from this list, so you can return the results once you have found all your files:
def construct_path(file_list, directory):
file_path_list = []
for dir, subdir, files in os.walk(directory):
for name in files:
if name in file_list:
file_path_list.append(os.path.join(dir, name))
file_list.remove(name)
if (len(file_list)==0): return file_path_list
return file_path_list
I'm wanting to use os.walk to search the cwd and subdirectories to locate a specific file and when found immediately break and change to that dir. I've seen many examples where it breaks after locating the file, but I can't figure out how to retrieve the path location so I can change dir.
Something like this?
f = 'filename'
for path, dirs, files in os.walk('.'):
if f in files:
os.chdir(path)
break
import os
required_file = "somefile.txt"
cwd = '.'
def get_dir_name(cwd, required_file):
for dirName, subdirList, fileList in os.walk(cwd):
for fname in fileList:
if fname == required_file:
change_to_dir = os.path.abspath(dirName)
return change_to_dir
change_to_dir = get_dir_name(cwd, required_file)
os.chdir(change_to_dir)
In my code, I'm able to search through a directory for a file with a specific name. How could I edit the code so that it first searches for folders with names ending with the word "output". In the below code, when I tried to include the commented out line, the whole thing refused to run. Any help on what I'm missing would be greatly appreciated
def test():
file_paths = []
filenames = []
for root, dirs, files in os.walk('/Users/Bashe/Desktop/121210 p2/'):
for file in files:
#if re.match("output", file):
if re.match("Results",file):
file_paths.append(root)
filenames.append(file)
return file_paths, filenames
To search files that are in a folder with name ending with the word "output":
for dirpath, dirs, files in os.walk(rootdir):
if not dirpath.endswith('output'):
continue # look in the next folder
# search files
for file in files: ...
If you don't want even to visit any directories that are not ending with "output":
if not rootdir.endswith('output'):
return # do not visit it at all
for dirpath, dirs, files in os.walk(rootdir):
assert dirpath.endswith('output')
dirs[:] = [d for d in dirs if d.endswith('output')] # edit inplace
# search files
for file in files: ...