Issue
I am trying to copy and automatically moves files from one directory to another. I have the basic code and after testing if it recognizes the data and it does by printing out the file names. When I use the shutil.move
it doesn't give me an output and it does not move the files.
I also want to be able to move files like this many times and I am trying to find a if statement for when a file exist for it to move on to the next file. Any Suggestions?
Forgive me for the xxx it is to cover up the file paths and names at work
However here is the code I have so far:
import os
import shutil
#Path to copy or move files from
path1 = r"C:xxx"
#Variable to list all the files in the directory
file_dir = os.listdir(path1)
#Test print to see if the directory can be accessed WORKED
#print(file_dir)
#variable for the files to be moved into whe they are moved/copied
fpath = r"C:xxx"
#For loop so go through every file in the directory
for file in file_dir:
#If statsment so the only files with .jpg will be moved
if file.endswith('.jpg'):
#Method to recursivly move each file
#path.join combines the two paths
shutil.move(os.path.join(file_dir,file), os.path.join(fpath, file))
My idea for the if staement:
if filename exist:
go to the next file
else:
shutil.move(os.path.join(file_dir,file), os.path.join(fpath, file))
Is there anyway to fix the files not moving and how to get this if statement to work.
Solution
This may accomplish what you are trying to achieve:
import os
import shutil
# Path to copy or move files from
source = os.getcwd()
# Path to move/copy files to
destination = os.path.join(source, 'images')
# For loop so go through every file in the directory
for file in os.listdir(source):
# If statement so only files with .jpg will be moved
if file.lower().endswith('.jpg'):
shutil.move(file, destination)
In the last line of your code, file_dir
is a list
(i.e., os.listdir(path1)
). This is where you may be getting an error. You cannot use the join()
function to concatenate lists
& strings.
Answered By - Seraph
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.