How to move and enter folders and subfolders in python [duplicate] - python

This question already has answers here:
Using os.walk() to recursively traverse directories in Python
(14 answers)
Closed 2 years ago.
i have a dataset and one folder and in this folder i have a few subfolder in them there is audio file i need to move on the whole subfolders and get the file and the path , i using python
osomeone has idea?
folder: dataset -> folders: rock,regge,hiphop,classic,disco,jazz,pop,blues,country,metal -> files: "name".wav
i need to enter each folder and get the file and path.
i have 100 files in folder.
i dont try nothing because i dont know how to do that

You should use os.walk
import os
for subdir, dirs, files in os.walk(rootdir):
for file in files:
filepath = subdir + os.sep + file
if filepath.endswith(".wav"):
print(filepath)

Related

How do I automate Python to navigate to other directories [duplicate]

This question already has answers here:
How do I list all files of a directory?
(21 answers)
Closed 1 year ago.
I am trying to make a code in Python where when it runs it will search a directory and its sub-directories for files ending with a file extension ".pdm". I want to note this is not on a personal computer but on a cloud provider. The variable current_dur is just a starting point to narrow down the search. The directory has to go at through at least 3 more folders in its sub-directories.
import os
current_dur = r'\\dmn1.MIR.com\MIRFILE\FS159\FIRSCODB\IR Data Modeling\PIR\IR - Information Report'
for item in os.listdir(current_dur):
if not os.path.isfile(item):
for file in os.listdir(item):
if file.endswith('.pdm'):
print(file)
It returns the error message [WinError 3] The system cannot find the path specified: 'Archive'
Have you tried using os.walk()?
import os
current_dur = r'\\dmn1.MIR.com\MIRFILE\FS159\FIRSCODB\IR Data Modeling\PIR\IR - Information Report'
pdm_files = []
for root, dirs, files in os.walk(current_dur):
for file in files:
if file.endswith('.pdm'):
pdm_files.append(os.path.join(root, file))

Recursively rename files in python [duplicate]

This question already has answers here:
Rename multiple files in a directory in Python
(15 answers)
Closed 3 years ago.
I have a folder named '12' and this folder contains following files:
import os
for root, dirs, files in os.walk('./12', topdown=True):
dirs.clear() #with topdown true, this will prevent walk from going into subs
for file in files:
print(file)
Output:
ab 1.jpg
ab 0.jpg
Now I want to replace spaces in the above files with an underscore to do this I have done:
import os
for root, dirs, files in os.walk('./12', topdown=True):
dirs.clear() #with topdown true, this will prevent walk from going into subs
for file in files:
r=file.replace(" ", "_")
os.rename(r, file)
In the above code when I print(r) it gives me value of space replaced by underscore i.e
ab__1.jpg
ab_0.jpg
But the os.rename function does not work and actual file names are not changed inside the folder. I get the following error for os.rename(r, file):
Traceback (most recent call last): File "demo.py", line 7, in
os.rename(r, file) FileNotFoundError: [Errno 2] No such file or directory: 'ab__1.jpg' -> 'ab 1.jpg'
How can I resolve this error ?
Edit:
My question is not a duplicate of Rename multiple files in a directory in Python because on the mentioned link they are using one for loop to recursively rename all the files in the current working directory. In my question I am using 2 for loops as renaming files is one sub part of my entire process, When I use two for loops I am encountering my error.
Perhaps you are intending to do os.rename("./12/" + file, ./12/" + r)? As you are modifying the files in the directory named 12, not the directory where the Python script was executed from.
My bad I had to provide absolute path to rename these files:
import os
cwd=os.getcwd()+'/12'
print(cwd)
for root, dirs, files in os.walk('./12', topdown=True):
dirs.clear() #with topdown true, this will prevent walk from going into subs
for file in files:
r=file.replace(" ", "_")
os.rename(os.path.join(cwd,file), os.path.join(cwd,r))
Use os.rename(file, r) instead of os.rename(r, file).

Rename part of the name in any files or directories in Python [duplicate]

This question already has answers here:
How to rename a file using Python
(17 answers)
Closed 3 years ago.
I have a root folder with several folders and files and I need to use Python to rename all matching correspondences. For example, I want to rename files and folders that contain the word "test" and replace with "earth"
I'm using Ubuntu Server 18.04. I already tried some codes. But I'll leave the last one I tried. I think this is really easy to do but I don't have almost any knowledge in py and this is the only solution I have currently.
import os
def replace(fpath, test, earth):
for path, subdirs, files in os.walk(fpath):
for name in files:
if(test.lower() in name.lower()):
os.rename(os.path.join(path,name), os.path.join(path,
name.lower().replace(test,earth)))
Is expected to go through all files and folders and change the name from test to earth
Here's some working code for you:
def replace(fpath):
filenames = os.listdir()
os.chdir(fpath)
for file in filenames:
if '.' not in file:
replace(file)
os.rename(file, file.replace('test', 'earth'))
Here's an explanation of the code:
First we get a list of the filenames in the directory
After that we switch to the desired folder
Then we iterate through the filenames
The program will try to replace any instances of 'test' in each filename with 'earth'
Then it will rename the files with 'test' in the name to the version with 'test' replaced
If the file it is currently iterating over is a folder, it runs the function again with the new folder, but after that is done it will revert back to the original
Edited to add recursive iteration through subfolders.

Recursively enter each subdirectory of a directory in Python [duplicate]

This question already has answers here:
Using os.walk() to recursively traverse directories in Python
(14 answers)
Closed 4 years ago.
I am new to Python and I am trying to write a function that will be able to enter inside a folder if there all files it should just print their names if it is a folder it should go inside it and print it's files, if there is a folder inside this folder it should also go inside and do that until there is nothing left. For now I haven't found a way to go that deep. Is there a way to do that recursively? How should I proceed my code for some reason doesn't enter all subdirectories. Thanks in advance
def list_files(startpath, d):
for root, dirs, files in os.walk(startpath):
for f in files:
print (f)
for di in dirs:
print (di)
list_files(di, d + 1)
list_files(path, 0)
May be you can check this answer:
Using os.walk() to recursively traverse directories in Python
which employs os.walk() method like this.
import os
# traverse root directory, and list directories as dirs and files as files
for root, dirs, files in os.walk("."):
path = root.split(os.sep)
print((len(path) - 1) * '---', os.path.basename(root))
for file in files:
print(len(path) * '---', file)

Using os.walk to get all files from dir and its subdirs [duplicate]

This question already has answers here:
Using os.walk() to recursively traverse directories in Python
(14 answers)
Closed 4 years ago.
I'm currently writing a python script which you can give a drive or folder, and it then iterates through every image on the drive or folder and moves them all into one folder.
My issue is that using os.walk, it isn't opening the subdirs automatically. As an example, say I chose the E: drive to scan. E: drives file structure;
E:
+ Folder1
- file.png
- file2.png
- files.jpg
The only file that my script will detect is files.jpg, as the other files are nested in a subdir, which os.walk does not open and check for files.
Here's the code I'm using as of right now;
# For each file in the drive
for folders, sub_folders, files in os.walk(drive):
# For each name in the files
for filename in files:
if filename == drive + "\\ImageSorter\\":
continue
file_name = os.path.splitext(filename)[0]
extension = os.path.splitext(filename)[1]
Is there a way to get os.walk to iterate through all subdirs on the drive, rather than just the first folder?
Try this code
import os
for root, dirs, files in os.walk("."):
path = root.split(os.sep)
print((len(path) - 1) * '---', os.path.basename(root))
for file in files:
print(len(path) * '---', file)

Categories

Resources