I have folder that has subfolders each with many different files.
I'd like to copy all of the files (not subdirectories) into one folder
import os
import shutil
src = r'C:\TEMP\dir'
dest = r'C:\TEMP\new'
src_files = os.listdir(src)
for file_name in src_files:
full_file_name = os.path.join(src, file_name)
if (os.path.isfile(full_file_name)):
shutil.copy(full_file_name, dest)
when I run the code, there is no error but no files is copied either.
I do not know what is wrong with the code.
You can try this
import os
import shutil
src = r'C:\TEMP\dir'
dest = r'C:\TEMP\new'
for path, subdirs, files in os.walk(src):
for name in files:
filename = os.path.join(path, name)
shutil.copy2(filename, dest)
Related
I have a question and I went all the other topics through with similar problems but I didn't get my solved.
I have a folder where two subfolders are. Inside of them are a lot of files, but I need just files with extension .trl. I need to copy them and save them in a new folder that is already created.
My code don't give me an error but I don't see any result. What I'm doing wrong?
import os
import shutil
import fnmatch
directory = "/home/.../test_daten"
ext = ('.trl')
dest_dir = "/home/.../test_korpus"
for root, dirs, files in os.walk(directory):
for extension in ext:
for filename in fnmatch.filter(files, extension+'.trl'):
source = (os.path.join(root, filename))
shutil.copy2(source, dest_dir)
Use os.walk() and find all files. Then use endswith() to find the files ending with .trl.
Sample code:
import os, shutil;
directory = "/home/.../test_daten";
dest_dir = "/home/.../test_korpus";
filelist = [];
for root, dirs, files in os.walk(directory):
for file in files:
filelist.append(os.path.join(root,file));
for trlFile in filelist:
if trlFile.endswith(".trl"):
shutil.copy(trlFile, dest_dir);
Maybe your problem is fnmatch.filter(files, extension+'.trl'). You have extension from for extension in ext: which will loop though the variable ext and give you a letter from it each time. Your extension+'.trl will be ..trl, t.trl, l.trl
import os
import shutil
directory = "/home/.../test_daten"
dest_dir = "/home/.../test_korpus"
for root, _, files in os.walk(directory): #Get the root, files
for x in files:
if x.endswith('.trl'): #Check the extension
shutil.copy2(f'{root}/{x}', dest_dir)
import os
import shutil
import fnmatch
source = "/home/.../test_daten"
ext = '*.trl'
target = "/home/.../test_korpus"
for root, _, files in os.walk(source):
for filename in fnmatch.filter(files, ext):
shutil.copy2(os.path.join(root, filename), target)
I have code as below to copy all *.csv files from different source folders, but i want to copy in different folders as per source, i could able to copy all csv files to single folder but i want it into different folders as source folders.
import os
import shutil
import fnmatch
dir = 'C:\\data\\projects\\'
patterns = ['project1','project2']
dest = 'D:\\data\\projects\\'
for root, dirs, files in os.walk(dir):
for pattern in patterns:
for filename in fnmatch.filter(files, '*.csv'):
source = (os.path.join(root, filename))
print(source)
shutil.copy(source, dest)
You could use os.path.relpath to extract the subpath for a general method, and os.makedirs to create missing directories on the destination:
...
for filename in fnmatch.filter(files, '*.csv'):
source = (os.path.join(root, filename))
print(source)
rel = os.path.relpath(root, dir)
curdest = os.path.join(dest, rel)
if not os.path.exists(curdest):
os.makedirs(curdest, exist_ok=True)
shutil.copy(source, curdest)
I found out how to do it with this script:
import os, sys, shutil, glob
if not os.path.exists('Files'):
os.makedirs('Files')
source_dir = os.path.join(os.environ["HOMEPATH"], "Desktop")
dest_dir = 'Files'
try:
for root, dirnames, filenames in os.walk(source_dir):
for file in filenames:
(shortname, extension) = os.path.splitext(file)
if extension == ".txt" :
shutil.copy2(os.path.join(root,file), os.path.join(dest_dir,
os.path.relpath(os.path.join(root,file),source_dir)))
except FileNotFoundError:
pass
But, it only copies the files in the path and not the in sub-folders
So for example here it copies the desktop .txt files, but it does not copy the files in the folders.
Thanks, have a good day.
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)
I'm trying to make a script that copies all the files other than the zipped files from a source folder to another destination folder and extract zipped files from the source folder to the destination, this is what i have come till this far:
import os
import zipfile
import shutil
myPath = "Source dir"
for root, dirs, files in os.walk(myPath):
for file in files:
if file.endswith('.zip'):
fh = open(file, 'rb')
z = zipfile.ZipFile(fh)
for name in z.namelist():
outpath = "destination dir"#Put the name of the destination folder
z.extract(name, outpath)
fh.close()
else:
fileList = os.listdir('source dir')
for f in fileList:
shutil.copy2(f, 'destination directory')
The code shows no error but there is no output too.
From Python Standard Library To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name) so you should write
fh = open(so.path.join(root,file))
to have the correct path.