how to move specific files from one folder to another? - python

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

Related

Python - os.walk won't copy files from multiple folders

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))

Copy pdfs in a directory to folders with the same name as the PDFs

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.

How can I delete files by extension in subfolders of a folder?

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)

Attempting to move Files but unable to move Folders via Python

I am trying to move files and folders from directory to another. I am currently facing two issues.
It only seems to move files but not any folders.
It only picks up the uppercase or lowercase.
Do you know what might be missing to do this. I could add an or statement statement with startswith but would like to see if there is a better way to do this.
import os
from os import path
import shutil
src = "C:/Users/test/documents/"
dst = "C:/Users/test/Documents/test"
files = [i for i in os.listdir(src) if i.startswith("C") and \
path.isfile(path.join(src, i))]
for f in files:
shutil.move(path.join(src, f), dst)
This will go through the source directory, create any directories that do not yet exist in the destination directory, and move the files from the source to the destination directory:
(As I understand it, this is what you want)
import os
import shutil
src = "C:/Users/test/documents/"
dst = "C:/Users/test/documents/test"
for src_dir, dirs, files in os.walk(src):
dst_dir = src_dir.replace(src, dst, 1)
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
for file_ in files:
src_file = os.path.join(src_dir, file_)
dst_file = os.path.join(dst_dir, file_)
if os.path.exists(dst_file):
os.remove(dst_file)
shutil.move(src_file, dst_dir)

Move child folder contents to parent folder in python

I have a specific problem in python. Below is my folder structure.
dstfolder/slave1/slave
I want the contents of 'slave' folder to be moved to 'slave1' (parent folder). Once moved,
'slave' folder should be deleted. shutil.move seems to be not helping.
Please let me know how to do it ?
Example using the os and shutil modules:
from os.path import join
from os import listdir, rmdir
from shutil import move
root = 'dstfolder/slave1'
for filename in listdir(join(root, 'slave')):
move(join(root, 'slave', filename), join(root, filename))
rmdir(join(root, 'slave'))
I needed something a little more generic, i.e. move all the files from all the [sub]+folders into the root folder.
For example start with:
root_folder
|----test1.txt
|----1
|----test2.txt
|----2
|----test3.txt
And end up with:
root_folder
|----test1.txt
|----test2.txt
|----test3.txt
A quick recursive function does the trick:
import os, shutil, sys
def move_to_root_folder(root_path, cur_path):
for filename in os.listdir(cur_path):
if os.path.isfile(os.path.join(cur_path, filename)):
shutil.move(os.path.join(cur_path, filename), os.path.join(root_path, filename))
elif os.path.isdir(os.path.join(cur_path, filename)):
move_to_root_folder(root_path, os.path.join(cur_path, filename))
else:
sys.exit("Should never reach here.")
# remove empty folders
if cur_path != root_path:
os.rmdir(cur_path)
You will usually call it with the same argument for root_path and cur_path, e.g. move_to_root_folder(os.getcwd(),os.getcwd()) if you want to try it in the python environment.
The problem might be with the path you specified in the shutil.move function
Try this code
import os
import shutil
for r,d,f in os.walk("slave1"):
for files in f:
filepath = os.path.join(os.getcwd(),"slave1","slave", files)
destpath = os.path.join(os.getcwd(),"slave1")
shutil.copy(filepath,destpath)
shutil.rmtree(os.path.join(os.getcwd(),"slave1","slave"))
Paste it into a .py file in the dstfolder. I.e. slave1 and this file should remain side by side. and then run it. worked for me
Use this if the files have same names, new file names will have folder names joined by '_'
import shutil
import os
source = 'path to folder'
def recursive_copy(path):
for f in sorted(os.listdir(os.path.join(os.getcwd(), path))):
file = os.path.join(path, f)
if os.path.isfile(file):
temp = os.path.split(path)
f_name = '_'.join(temp)
file_name = f_name + '_' + f
shutil.move(file, file_name)
else:
recursive_copy(file)
recursive_copy(source)
Maybe you could get into the dictionary slave, and then
exec system('mv .........')
It will work won't it?

Categories

Resources