This question already has answers here:
How do I list all files of a directory?
(21 answers)
Closed 4 years ago.
In this a variable there is a folder called main_folder.
This folder has two folders:
111,222
I need to get the names of these folders in a list.
Tried this:
a = r'C:\Users\user\Desktop\main_folder'
import os
for root, dirs, files in os.walk(a):
print(dirs)
gives:
['111', '222'] # <--------------This only needed
[]
[]
How to keep only the first list and not the empty ones which I think describe the contents of these folders since they don't have folders.
This function will do the job:
import os
def get_immediate_subdirectories(a_dir): ##a_dir is the path of the main folder
return [name for name in os.listdir(a_dir) ## returns all the immediate subfolders
if os.path.isdir(os.path.join(a_dir, name))] ## keeps checking the name + file is here
Calling Function:
get_immediate_subdirectories("Path")
Iterate just once via next:
import os
a = r'C:\Users\user\Desktop\main_folder'
walker = os.walk(a)
res = next((dirs for _, dirs, _ in walker), [])
If necessary, you can continue iterating walker via additional next calls.
Related
This question already has answers here:
How to use glob() to find files recursively?
(28 answers)
Closed 1 year ago.
I am new to the programing world and I have hit a snag on a piece of code.
What I have: I have a piece of code that identifies all .MP4 files and calculates the size of the files within a directory. So far I can only apply this code to a specific folder that I input manually. But the code works.
Problem: I would like to apply what I have to multiple folders within a directory. I have several folders with years in the file path and I would like to apply this code to each year individually. For example: I need a piece of code/direction to code that can allow me to run this code on all folders with '2021' in the name.
Any pointers or suggestions are welcome.
# import module
import os
# assign size
size = 0
# assign folder path
Folderpath = r'C:\file_path_name_here'
# get size
for path, dirs, files in os.walk(Folderpath):
for f in files:
if not f.endswith('.MP4'):
continue
else:
fp = os.path.join(path, f)
size += os.path.getsize(fp)
# display size
print("Folder size: " + str(size))
You can use glob for that.
If i understand you correctly you want to iterate through all Folders right?
I myself am not a routined coder aswell but i use it in for a Script where i have to iterate over an unknown number of files and folders. In my case PDF's
which then get scanned/indexed/merged...
This obviously returns a list of of files with which you then could workd through. os.path commonpath is also handy for that.
def getpdflisting(fpath):
filelist = []
for filepath in Path(os.path.join(config['Ordner']['path'] +\
fpath)).glob('**/*.pdf'):
filelist.append(str(filepath))
if filelist:
filelist = [x for x in filelist if x]
logger.info(filelist)
return filelist
Or even better https://stackoverflow.com/a/66042729/16573616
This question already has answers here:
How do I list all files of a directory?
(21 answers)
Closed 3 years ago.
I have a directory with my .py file and I have another directory where I am writing files to. How can I get a os.listdir of the second directory without using os.chdir?
Edit: Sorry seems like there are 2 parts to my implementation. My current code is this:
files = [f for f in os.listdir(2nd_d) if os.path.isfile(f)]
It currently returns an empty list when there are some files in the directory.
Just use the full path of that other directory.
dir1_contents = os.listdir('C://path/to/my/dir1')
dir2_contents = os.listdir('C://path/to/my/dir2')
Why not just do a full path check?
import numpy as np
import os
base = 'C:/Users/user/desktop/files/'
for i in range(50):
temp = np.random.normal(0, 1, (100, 100))
np.save(f'{base}File_{i}.npy', temp)
files = os.listdir(base)
This question already has answers here:
Rename multiple files inside multiple folders
(3 answers)
Closed 4 years ago.
i'm trying to erase all indexes (characters) except the last 4 ones and the files' extension in python. for example:
a2b-0001.tif to 0001.tif
a3tcd-0002.tif to 0002.tif
as54d-0003.tif to 0003.tif
Lets say that folders "a", "b" and "c" which contains those tifs files are located in D:\photos
there many of those files in many folders in D:\photos
that's where i got so far:
import os
os.chdir('C:/photos')
for dirpath, dirnames, filenames in os.walk('C:/photos'):
os.rename (filenames, filenames[-8:])
why that' not working?
So long as you have Python 3.4+, pathlib makes it extremely simple to do:
import pathlib
def rename_files(path):
## Iterate through children of the given path
for child in path.iterdir():
## If the child is a file
if child.is_file():
## .stem is the filename (minus the extension)
## .suffix is the extension
name,ext = child.stem, child.suffix
## Rename file by taking only the last 4 digits of the name
child.rename(name[-4:]+ext)
directory = pathlib.Path(r"C:\photos").resolve()
## Iterate through your initial folder
for child in directory.iterdir():
## If the child is a folder
if child.is_dir():
## Rename all files within that folder
rename_files(child)
Just note that because you're truncating file names, there may be collisions which may result in files being overwritten (i.e.- files named 12345.jpg and 22345.jpg will both be renamed to 2345.jpg, with the second overwriting the first).
This question already has answers here:
Python error os.walk IOError
(2 answers)
Closed 4 years ago.
I am trying to create a list of paths for multiple files with the same name and format from different folders. I tried doing this with os.walk with the following code:
import os
list_raster = []
for (path, dirs, files) in os.walk(r"C:\Users\Douglas\Rasters\Testing folder"):
for file in files:
if "woody02.tif" in file:
list_raster.append(files)
print (list_raster)
However, this only gives me two things
the file name
All file names in each folder
I need the the full location of only the specified 'woody02.txt' in each folder.
What am I doing wrong here?
The full path name is the first item in the tuples in the list returned by os.walk, so it is assigned to your path variable already.
Change:
list_raster.append(files)
to:
list_raster.append(os.path.join(path, file))
In the example code you posted you are appending files to your list instead of just the current file, in order to get the full path and file name for the current file you would need to change your code to something like this:
import os
list_raster = []
for (path, dirs, files) in os.walk(r"C:\Users\Douglas\Rasters\Testing folder"):
for file in files:
if "woody02.tif" in file:
# path will hold the current directory path where os.walk
# is currently looking and file would be the matching
# woody02.tif
list_raster.append(os.path.join(path, file))
# wait until all files are found before printing the list
print(list_raster)
This question already has answers here:
Getting a list of all subdirectories in the current directory
(34 answers)
Closed 7 years ago.
I have a directory and I need to make a path list for the sub directories.
For example my main directory is
C:\A
which contains four different sub directories : A1,A2,A3,A4
I need a list like this:
Path_List = ["C:\A\A1","C:\A\A2","C:\A\A3","C:\A\A4"]
Cheers
import os
base_dir = os.getcwd()
sub_dirs = [os.path.join(base_dir, d) for d in os.listdir(base_dir)]
You could (and should, i think) use os module, wich is easy to use and provides a lot of stuff to deal with paths.
I wont say anymore, because your question is vague and shows no effort on searching. You are welcome!!
sub_dirs = os.listdir(os.getcwd()) ## Assuming you start the script in C:/A
path_list = []
for i in sub_dirs:
path_list.append(os.path.join(os.getcwd(),i))
Dirty and fast.