Im trying to copy directorys and files from
/var/media/KODI/connman
to
/storage/.cache/connman
Inside the connman folder is a file and another folder with a file inside
The problem im having is that only the folder and its file are being copied the file in the connman folder is not. the code im working on is:
drive = xbmcaddon.Addon().getSetting('Drive')
connman = ('connman/')
src_network = ('/storage/.cache/')
for file_or_dir in os.listdir(drive + connman):
path = os.path.join(drive + connman,file_or_dir)
if os.path.isdir(path):
dir = file_or_dir
src = os.path.join(drive + connman,dir)
dst = os.path.join(src_network,dir)
try:
copytree(src,dst)
except Exception as e:
log(("copytree",e,src,dst))
Try this.
from distutils.dir_util import copy_tree
copy_tree("/source_folder", "/target_folder")
Related
The Problem is there's an error when i run the script called
this
terminal log
here's the script:
import os
# Get a list of all the files in the current directory
files = os.listdir('.')
# Sort according to extention
files.sort(key=lambda x: x.split('.')[-1])
# for loop to itrate thru list
for file in files:
# base name and extention split eg. joe .mama (folder: mama; folder chya andar: joe)
name, extension = os.path.splitext(file)
#pahale directory banwachi, if dosent exist
directory = extension[1:]
if not os.path.exists(directory):
os.makedirs(directory)
# Move the file into the directory for its file extension
os.rename(file, f'{directory}/{file}')
any help will be appreciated thanks : ) <3
the script was working fine when i ran it for the fist time but when i ran it for second time there's this error
Your code isn't handling files with no extension, add some handling for that. for example;
import os
# Get a list of all the files in the current directory
files = os.listdir('.')
# Sort according to extention
files.sort(key=lambda x: x.split('.')[-1])
# for loop to itrate thru list
for file in files:
# base name and extention split eg. joe .mama (folder: mama; folder chya andar: joe)
name, extension = os.path.splitext(file)
#pahale directory banwachi, if dosent exist
directory = extension[1:] if extension[1:] != '' else 'None'
if not os.path.exists(directory):
os.makedirs(directory)
# Move the file into the directory for its file extension
os.rename(file, f'{directory}/{file}')
here's a better version of the code I wrote
import os
import shutil
# Sort and move files according to their extension
# Get a list of all the files in the current directory
files = os.listdir('.')
# Sort the files by extension
files.sort(key=lambda x: os.path.splitext(x)[1])
# Iterate through the files
for file in files:
# Split the file name and extension
name, extension = os.path.splitext(file)
# Create the destination directory for the file
if extension != '':
directory = extension[1:]
if not os.path.exists(directory):
os.makedirs(directory)
else:
directory = 'None'
# Move the file to the destination directory
shutil.move(file, os.path.join(directory, file))
thanks for the help : )
I have problems solving a task. Below you can see my code. I want to work with sub-sub-folders too but my code only moves the sub-folders. How can I do this recursively that it moves all folders in main folder?
path = (r"C:\Users\Desktop\testfolder")
os.chdir(path)
all_files = list(os.listdir())
outputs = os.getcwd()
for files in all_files:
try:
inputs = glob.glob(files + "\\*")
for a in inputs:
shutil.move(a, outputs)
except:
pass
for files in os.listdir("."):
dir_folder = files[:32]
if not os.path.isdir(dir_folder):
try:
os.mkdir(dir_folder)
except:
pass
Here is the new code, that will maintain the folder structure in the output folder as it was in the input folder
from pathlib import Path
import shutil
import os
for path, dir_folder, files in os.walk('./test_folder'):
for file in files:
full_path = os.path.join(path,file)
## Create the path to the subfolder
sub_folder_path = '/'.join(path.split('/')[2:])
# Create output path by joining subfolder path and output directory
output_path = os.path.join(outputs, sub_folder_path)
# Create the output path directory structure if it does not exists, ignore if it does
Path(output_path).mkdir(parents=True, exist_ok=True)
# Move file
shutil.move(full_path, output_path)
You can use os.walk to recursively visit each folder and sub folder and then move all the files in that folder.
import shutil
import os
for path, dir_folder, files in os.walk(input_folder):
for file in files:
full_path = os.path.join(path,file)
move_path = os.path.join(output_path,file)
print(move_path)
shutil.move(full_path, move_path)
print(file)
Where output_path is the path to the folder you move to move the files to.
This will not create the same folder structure in output folder, just move all the files there, do you also want to maintain structure in output folder? If so, I can edit my answer to reflect that
I have a python script that must check first if folder exist in giving path then if exist delete the existing one then copy the new one from the source. if does't exist just copy the new folder.
the problem is that in the source path if i have folder the system will check if the folder exist in the destination and delete and copy if exist.
what i want is to just check for one folder name "test" and then if does't exist copy the new folder if exist delete and copy.
code:
import os
import shutil
from os import path
import datetime
src = "I:/"
src2 = "I:/test"
dst = "C:/Users/LT GM/Desktop/test/"
dst2 = "C:/Users/LT GM/Documents/"
dst3 = "C:/Users/LT GM/Documents/Visual Studio 2017"
def main():
copy()
def copy():
#go through the src files and folders
for root,dirs,files in os.walk(src):
try:
for folder in dirs:
#return folder name
full_folder_name = os.path.join(src, folder)
print("folder : ",full_folder_name)
#check if folder exits
if os.path.exists(dst):
print("folder exist")
#delete folder
shutil.rmtree(dst)
print("the deleted folder is :{0}".format(dst))
#copy the folder as it is (folder with the files)
copieddst = shutil.copytree(src2,dst)
print("copy of the folder is done :{0}".format(copieddst))
else:
print("folder does Not Exist")
#copy the folder as it is (folder with the files)
copieddst = shutil.copytree(src2,dst)
print("copy of the folder is done :{0}".format(copieddst))
except Exception as e:
print(e)
try:
for name in files:
full_file_name = os.path.join(src, name)
print("files: ",full_file_name)
#check for pdf extension
if name.endswith("pdf"):
#copy files
shutil.copy(full_file_name, dst2)
#check for doc & docx extension
elif name.endswith("docx") or name.endswith("doc"):
#copy files
shutil.copy(full_file_name, dst3)
print("word files done")
print("pdf files done")
except Exception as e:
print(e)
if __name__=="__main__":
main()
why do you even check? Just rmtree the destination and ignore the error if it doesn't exist. You're not getting any significant saving by first checking, you're just making your code more complex.
why do you delete src for every folder you're copying? Just delete it once before the loop
also you should probably copy the sub-folders of src in sub-folders of dst rather than dump everything in src
os.walk will recursively walks through all the directories under the root (and thus their directories, and theirs, ...), that really doesn't seem to be what you want here,
your path management is weird as hell, why do you have two different sources and three destinations used completely inconsistently?
Hello there I am new programmer trying to write a program to copy all jpegs found on my computer over to a folder.
The program seems to be working in the sense that it finds all the jpegs but when it comes to copying them over to the new folder nothing happens.
Can someone please help me? Thanks
Ive made sure that the permissions on the destination folder are good to go.
# program to go through all directories
# and copy found jpg files
# to new folder
import os
from shutil import copy2
#replace below with your directory / destination folder
src = "/home/coyotejoe"
dst = '/home/coyotejoe/Desktop/JPG'
for root, dirs, files in os.walk(src, topdown=True):
for name in files:
if name.endswith('jpg'):
try:
copy2(os.path.join(src,name), os.path.join(dst, name))
except:
pass
prints the names of all jpegs but destination folder is still blank
I tried your code on my computer on a directory which has 'png' files and it works.
#replace below with your directory / destination folder
src = "C:\S\SODTEST\SODTEST"
dst = 'C:\S\SODTEST'
import os
from shutil import copy2
for root, dirs, files in os.walk(src, topdown=True):
for name in files:
if name.endswith('png'):
try:
copy2(os.path.join(src,name), os.path.join(dst, name))
except Exception as e:
print(e)
Observe the exception you are getting instead of makine it fail silently.
You are os-walking and ignoring subdirectories. If you have subdirectories with jpgs in them) use copy2(os.path.join(root, name), os.path.join(dst, name)).
im trying to copy a .txt file from one dest to another. This code is running but the file isnt copying. What am i doing wrong?
import shutil
import os
src = "/c:/users/mick/temp"
src2 = "c:/users/mick"
dst = "/c:/users/mick/newfolder1/"
for files in src and src2:
if files.endswith(".txt"):
shutil.copy(files, dst)
Your for loop isn't actually searching through the files of each of your sources. In addition your for loop isn't looping through each of the sources but rather the letters in src and src2 that are present in both. This adjustment should handle what you need.
import os
src = ["c:/users/mick/temp", "c:/users/mick"]
dst = "c:/users/mick/newfolder1/"
for source in src:
for src_file in os.listdir(source):
if src_file.endswith(".txt"):
old_path = os.path.join(source, src_file)
new_path = os.path.join(dst, src_file)
os.rename(old_path, new_path)
You shouldn't need shutil for this situation as it is simply a more powerful os.rename that attempts to handle different scenarios a little better (to my knowledge). However if "newfolder1" isn't already existant than you will want to replace os.rename() with os.renames() as this attempts to create the directories inbetween.
shutils is useful for copying, but to move a file use
os.rename(oldpath, newpath)
I know the question is little older. But Here are the simple way to achieve your task. You may change the file extension as you wish. For copying you may use copy() & for moving yo may change it to move(). Hope this helps.
#To import the modules
import os
import shutil
#File path list atleast source & destination folders must be present not everything.
#*******************************WARNING**********************************************
#Make sure these folders names are already created while using the 'move() / copy()'*
#************************************************************************************
filePath1 = 'C:\\Users\\manimani\\Downloads' #Downloads folder
filePath2 = 'F:\\Projects\\Python\\Examples1' #Downloads folder
filePath3 = 'C:\\Users\\manimani\\python' #Python program files folder
filePath4 = 'F:\\Backup' #Backup folder
filePath5 = 'F:\\PDF_Downloads' #PDF files folder
filePath6 = 'C:\\Users\\manimani\\Videos' #Videos folder
filePath7 = 'F:\\WordFile_Downloads' #WordFiles folder
filePath8 = 'F:\\ExeFiles_Downloads' #ExeFiles folder
filePath9 = 'F:\\Image_Downloads' #JPEG_Files folder
#To change the directory from where the files to look // ***Source Directory***
os.chdir(filePath8)
#To get the list of files in the specific source directory
myFiles = os.listdir()
#To move all the '.docx' files to a different location // ***Destination Directory***
for filename in myFiles:
if filename.endswith('.docx'):
print('Moving the file : ' + filename)
shutil.move(filename, filePath4) #Destination directory name
print('All the files are moved as directed. Thanks')
import os, shutil
src1 = "c:/users/mick/temp/"
src2 = "c:/users/mick/"
dist = "c:/users/mick/newfolder"
if not os.path.isdir(dist) : os.mkdir(dist)
for src in [src1, src2] :
for f in os.listdir(src) :
if f.endswith(".txt") :
#print(src) # For testing purposes
shutil.copy(src, dist)
os.remove(src)
I think the error was that you were trying to copy a directory as a file, but you forgot to go through the files in the directory. You were just doing shutil.copy("c:/users/mick/temp/", c:/users/mick/newfolder/").