I have a folder, which contains many subfolders, each containing some videos and .srt files. I want to loop over the main folder so that all the .srt files from all subfolders are deleted.
Here is something I tried-
import sys
import os
import glob
main_dir = '/Users/Movies/Test'
folders = os.listdir(main_dir)
for (dirname, dirs, files) in os.walk(main_dir):
for file in files:
if file.endswith('.srt'):
os.remove(file)
However, I get an error as follows-
FileNotFoundError: [Errno 2] No such file or directory: 'file1.srt'
Is there any way I can solve this? I am still a beginner so sorry I may have overlooked something obvious.
You need to join the filename with the location.
import sys
import os
import glob
main_dir = '/Users/Movies/Test'
folders = os.listdir(main_dir)
for (dirname, dirs, files) in os.walk(main_dir):
for file in files:
if file.endswith('.srt'):
source_file = os.path.join(dirname, file)
os.remove(source_file)
Related
I couldn't find a suitable answer so I asked here.
My folder organized like this:
F:\WORKS\dataset\SOB\ben
and "ben" has three sub-folders "ad", "fib" & "pot". And all these subfolders have a same subfolder named 'XC' in them. 'XC' has different type of ".png" files. No, I want to read all the "XC" subfolders ".png" files at once with python.
Is that possible? I need this because I have to relocate all "XC" subfolders file at one place.
Thanks.
I have tried to Solve it, but furthest I can get to relocate all ".png" files for 'ben' folder at once.
The code I tried:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os
from os import listdir
from tqdm import tqdm
import shutil
%matplotlib inline
os.mkdir('augmented')
os.mkdir('augmented/ben')
def getListOfFiles(dirName):
listOfFile = os.listdir(dirName)
allFiles = list()
for entry in listOfFile:
fullPath = os.path.join(dirName, entry)
if os.path.isdir(fullPath):
allFiles = allFiles + getListOfFiles(fullPath)
else:
allFiles.append(fullPath)
return allFiles
files_ben = getListOfFiles('/content/drive/MyDrive/Works/dataset/SOB/ben')
for f in files_ben:
if f.endswith('.png'):
shutil.copy(f,'augmented/ben')
import os
# Set the directory path
directory = r"F:\WORKS\dataset\SOB\ben"
# Loop over all the subdirectories in the directory
for root, dirs, files in os.walk(directory):
# Check if the current directory is an XC directory
if os.path.basename(root) == "XC":
# Loop over all the files in the directory
for file in files:
# Check if the file is a PNG file
if file.endswith(".png"):
# Do something with the file
print(os.path.join(root, file))
I have this script that hopefully moves all the files in multiple folders into a new folder. I used the os.walk and shtil.copy functions. However the script does not work.
Here is the script:
import os
import shutil
for root, dirs, filename in os.walk(r"C:\Users\edward\OneDrive\Suspensia Pictures"):
MoveFrom = r"C:\Users\edward\OneDrive\Suspensia Pictures"
MoveTo = r"C:\Users\edward\OneDrive\Pics"
shutil.copy(os.path.join(MoveFrom, filename), os.path.join(MoveTo, filename))
Here is the error I get:
TypeError: join() argument must be str, bytes, or os.PathLike object, not 'list'
import os
import shutil
from pathlib import Path
for path, subdirs, files in os.walk(r"C:\Users\edward\OneDrive\Suspensia Pictures"):
MoveFrom = r"C:\Users\edward\OneDrive\Suspensia Pictures"
MoveTo = r"C:\Users\edward\OneDrive\Pics"
for name in files:
shutil.copy(os.path.join(path, name), Path(MoveTo))
As the os.walk documentation said,
filenames is a list of the names of the non-directory files in dirpath.
which means that the filename in your code is type of list and that is not acceptable type for join().
Here's a possible way to solve it,
import os
import shutil
files: list
for root, dirs, files in os.walk(r"."):
source_path = r"."
target_path = r"../test"
for file in files:
if os.path.isfile(os.path.join(source_path)):
shutil.copy(os.path.join(source_path, file), os.path.join(target_path, file))
One thing that you should consider is that the files from the result of os.walk would be the files in each folder under the root, which is recursive. So, this script only is able to handle the files in the depth 1.
For moving all the files in each of the folder under your specific directory, this script may work.
import os
import shutil
files: list
for root, dirs, files in os.walk(r"."):
target_path = r"../test"
for file in files:
source_path = os.path.join(root, file)
shutil.copy(source_path, os.path.join(target_path, file))
There is a code that moves files from one directory to another, but it doesn't move folders.
import os,glob
import shutil
inpath = str5
outpath = str6
os.chdir(inpath)
for file in glob.glob("*.*"):
shutil.move(inpath+'/'+file,outpath)
How to make it move both files and folders to the specified directory?
*.* selects files that have an extension, so it omits sub-folders.
Use * to select files and folders.
Then you should see your desired result.
for file in glob.glob("*"):
shutil.move(inpath+'/'+file,outpath)
You can use os.listdir to get all the files and folders in a directory.
import os
import shutil
def move_file_and_folders(inpath, outpath):
for filename in os.listdir(inpath):
shutil.move(os.path.join(inpath, filename), os.path.join(outpath, filename))
In your case,
inpath = <specify the source>
outpath = <specify the destination>
move_file_and_folders(inpath, outpath)
Friends, I'm working with some folders and I'm having a hard time moving files from one folder to another. I tried to use the command shutil.move (), but I can only move one file or all that are present in the folder. I would like to move only a few files present in the folder. I thought about making a list with the name of the files, but it didn't work, could someone help me please?
follow my code:
import shutil
source = r'C:\Users1'
destiny = r'C:\Users2'
try:
os.mkdir(destiny)
except FileExistsError as e:
print (f'folder {destiny} already exists.')
for root, dirs, files in os.walk(source):
for file in files:
old_way = os.path.join(root, file)
new_way = os.path.join(destiny, file)
if ['arq1','arq2'] in file:
shutil.move(old_way, new_way)
from shutil import copyfile
import os
from os import listdir
from os.path import isfile, join
source = '/Users/xxx/path'
destiny = '/Users/xxx/newPath'
onlyfiles = [f for f in listdir(source) if isfile(join(source, f))]
for file in onlyfiles:
if ['arq1','arq2'] in file:
src = source+"/"+file
dst = destiny+"/"+file
copyfile(src,dst)
If the file is already in the new directory it will automatically replace it
I want to put the pdfs I have in a directory in to the folders with the same name. Those folders with the same name have already been created and are in the same directory as the pdf files I want to move in to them.
I am relatively new at python and have not gotten very far on the code. Currently when I run the below it only prints the .pdf files but does not print the subfolders within the directory (that is besides the point but I am not sure why I cant see the sub folders in the directory in the below code.)
import os
from shutil import copyfile
path_to_files = "C:\\tmp\\all_files_converted\\"
def copy_documents(file_path):
for f in os.listdir(file_path):
print(f)
copy_documents(path_to_files)
folders in directory C://tmp//all_files_converted//
pdf files with the same name as the folders in the same directory C://tmp//all_files_converted//
You can use pathlib and shutil to perform this:
from pathlib import Path
from shutil import move
path_to_files = Path(r"C:\tmp\all_files_converted")
for pdf_path in path_to_files.glob("*.pdf"):
dir_path = path_to_files / pdf_path.stem
dir_path.mkdir()
move(pdf_path, dir_path / pdf_path.name)
You can use shutil.move(src, dst)
import shutil
shutil.move(src, dst)
import os
from shutil import copyfile
from glob import glob
path_to_files = "pasta"
def copy_documents(path_to_files):
# os.path is a module to work with file paths
# Using the module glob to list all pdf files of a folder
for file_path in glob(os.path.join(path_to_files, "*.pdf")):
# basename will return the filename without the rest of the path ie: "something.pdf"
pdf_file_name = os.path.basename(file_path)
dest_folder = os.path.join(path_to_files, pdf_file_name[:-4])
print(f"Copy {file_path} to {dest_folder}")
copyfile(file_path, os.path.join(dest_folder, pdf_file_name))
copy_documents(path_to_files)
I recommend reading https://docs.python.org/3/library/os.path.html and https://docs.python.org/3/library/glob.html
for more info.