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/").
Related
I am trying to create a script to move all the picture files from one folder to another. I have found the script that works for this, except it doesn't work if the extensions are in capitals. Is there an easy way around this?
Current code:
import shutil
import os
source = "C:/Users/Tonello/Desktop/"
dest = "C:/Users/Tonello/Desktop/Pictures/"
files = os.listdir(source)
for f in files:
if os.path.splitext(f)[1] in (".jpg", ".gif", ".png"):
shutil.move(source + f, dest)
You could lowercase the extension before checking it:
if os.path.splitext(f)[1].lower() in (".jpg", ".gif", ".png"):
# Here --------------^
i want a python script that do these three tasks:
check if the path contains word file copied to specific destination
check if the path contains pdf files copied to specific destination
check if the path contains directory and copy the hole folder to
specific destination.
for this reason i am using the os.walk() to list the dirs and files of the path
and i am using shutil library to copy files and dirs.
code
import os
from distutils.dir_util import copy_tree
import shutil
from os import path
import datetime
def main():
src = "C:/Users/LT GM/Desktop/Python_files/"
dst2 = "C:/Users/LT GM/Desktop/"
for root,dirs,files in os.walk(src):
for name in files:
print("files: ",os.path.join(root,name))
for name in dirs:
copieddst = copy_tree(src,dst2)
print("directory: ",os.path.join(root,name))
print(" coppied directory :{0}".format(copieddst) )
# make a duplicate of an existing file
if path.exists(src):
# get the path to the file in the current directory
print("****")
src = path.realpath("pandas.pdf")
#seperate the path from the filter
head, tail = path.split(src)
print("path:" +head)
print("file:" +tail)
dst =str(datetime.date.today()) + tail
# nowuse the shell to make a copy of the file
shutil.copy(src, dst)
if __name__=="__main__":
main()
the problem is that i can copy the files or the content of the directory. not the hole directory and how to check if its pdf or doc files?
If you want to copy directory rather than file, then use shutil.copytree. In usage it is similiar to shutil.copy2, that is:
import shutil
shutil.copytree('mydir', 'mydircopy')
Note that by default dirs_exist_ok is False meaning that destination should not exist, when shutil.copytree is launched.
I am working with Python3 and am trying to change the names of files in multiple subdirectories to match the folder name. My directory looks like this:
path: C:\Users\Me\Project
In the path, I have the following folders: alldata, folderA, folderB, folderC
FolderA, folderB, and folderC, each contain a file called data.csv
I want to add the letter name of the folder (e.g., A, B, C) to the file (e.g., dataA.csv) inside the folder and then move all these renamed files to "alldata"
I really appreciate the help!
This one might be a little hardcoded, but is probably more understandable for people who are just starting out in Python:
import os
import shutil
# Enter the 'Project' folder
os.chdir('C:\\Users\\Me\\Project')
# Filter for folders that contain the word 'folder'
folders = [folder for folder in os.listdir() if 'folder' in folder]
for folder in folders:
# Get the last letter of every folder
suffix = folder[-1]
# Build source and destination path for the csv files
source = folder + '\\data.csv'
dest = 'alldata\\data' + suffix + '.csv'
shutil.move(source, dest)
The 'os' module in python gives you access to functions that deal with folders and files. For example, there are functions in the os module to move, copy, rename, delete folders and files. Try this for example:
import os
basePath = "C:\\Users\\Me\\Project\\"
# Rename and move the data.csv file in folderA to dataA.csv in the alldata folder
os.rename(basePath + "folderA\\data.csv", basePath + "alldata\\dataA.csv")
# Rename and move the data.csv file in folderB to dataB.csv in the alldata folder
os.rename(basePath + "folderB\\data.csv", basePath + "alldata\\dataB.csv")
# Rename and move the data.csv file in folderC to dataC.csv in the alldata folder
os.rename(basePath + "folderC\\data.csv", basePath + "alldata\\dataC.csv")
# Make sure that they moved as intended
filesInAllDataFolder = os.listdir(basePath + "alldata\\")
print(filesInAllDataFolder)
The os module is super handy and I guarantee you'll use it a lot, so play with it!
This works for me:
import os
def scan_dir(folder):
for name in os.listdir(folder):
path = os.path.join(folder, name)
if os.path.isfile(path):
if 'data' in path:
dir_name = path.split('/')[-2]
new_name_path = path[:-3]+dir_name+'.csv'
new_name_path = new_name_path.split('/')
new_name_path[-2] = 'alldata'
new_name_path = "/".join(new_name_path)
os.rename(path, new_name_path)
else:
scan_dir(path)
directory = 'C:\Users\Me\Project'
scan_dir(directory)
I have a directory that literally has 3000+ folders (all with subfolders).
What I need to be able to do is to look through the directory for those files and move them to another folder. I've done some research and I see that shutil is used to move files, but i'm unsure how to input a list of files to look for.
For example, in the directory, I would like to take the following folders (and their subfolders) and move them to another folder called "Merge 1"
1442735516927
1442209637226
1474723762231
1442735556057
1474723762187
1474723762286
1474723762255
1474723762426
1474723762379
1474723762805
1474723762781
1474723762936
1474723762911
1474723762072
1474723762163
1474723762112
1442209642695
1474723759389
1442735566966
I'm not sure where to start with this so any help is greatly appreciated. Thanks!
Combining os and shutil, following code should answer your specific question:
import shutil
import os
cur_dir = os.getcwd() # current dir path
L = ['1442735516927', '1442209637226', '1474723762231', '1442735556057',
'1474723762187', '1474723762286', '1474723762255', '1474723762426',
'1474723762379', '1474723762805', '1474723762781', '1474723762936',
'1474723762911', '1474723762072', '1474723762163', '1474723762112',
'1442209642695', '1474723759389', '1442735566966']
list_dir = os.listdir(cur_dir)
dest = os.path.join(cur_dir,'/path/leadingto/merge_1')
for sub_dir in list_dir:
if sub_dir in L:
dir_to_move = os.path.join(cur_dir, sub_dir)
shutil.move(dir_to_move, dest)
I am new to Python and attempting to write an automated testing program. More specifically, I am trying to copy several .xlsx files from one directory to another. I've researched pretty thoroughly and am partially there. My code is below, which does not return and errors, but does not accomplish what I am trying to do. I believe my code is not granular enough (I am getting stuck at the directory level). In a nutshell: File A contains c, d, e, f.1, f.2, f.3 (all Excel docs). File B is empty. I am trying to copy f.1, f.2, and f.3 into File B. I believe I need to add the startswith function at some point, too. Any help is appreciated. Thanks!
import os
import shutil
import glob
source = 'C:/Users/acars/Desktop/a'
dest1 = 'C:/Users/acars/Desktop/b'
src_files = os.listdir('C:/Users/acars/Desktop/a')
for file_name in src_files:
full_file_name = os.path.join('C:/Users/acars/Desktop/a','a') #'a' incorrect
if (os.path.isfile(full_file_name)):
shutil.copy(full_file_name, dest1)
else:
break
Use the variables source and dest1:
source = 'C:/Users/acars/Desktop/a'
dest1 = 'C:/Users/acars/Desktop/b'
src_files = os.listdir(source)
for file_name in src_files:
if not file_name.startswith('f'):
continue
src = os.path.join(source, file_name) # <--
dst = os.path.join(dest1, file_name) # <--
shutil.copy(src, dst)