Reputation: 575
shutil.move(src, dst) is what I feel will do the job, however, as per the Python 2 documentation:
shutil.move(src, dst) Recursively move a file or directory (src) to another location (dst).
If the destination is an existing directory, then src is moved inside that directory. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics.
This is a little bit different than my case as below:
Before the move: https://snag.gy/JfbE6D.jpg
shutil.move(staging_folder, final_folder)
After the move: https://snag.gy/GTfjNb.jpg
This is not what I want, I want all the content in the staging folder be moved over to under folder "final" , I don't need "staging" folder itself.
Upvotes: 4
Views: 9958
Reputation: 676
You can use shutil.copytree()
to move all contents in staging_folder to final_folder without moving the staging_folder . Pass the argument copy_function=shutil.move
when calling the function.
For Python 3.8:
shutil.copytree('staging_folder', 'final_folder', copy_function=shutil.move, dirs_exist_ok=True)
For Python 3.7 and below:
beware that the paramater dirs_exist_ok
is not supported. The destination final_folder must not already exist as it will be created during moving.
shutil.copytree('staging_folder', 'final_folder', copy_function=shutil.move)
>>> os.listdir('staging_folder')
['file1', 'file2', 'file3']
>>> os.listdir('final_folder')
[]
>>> shutil.copytree('staging_folder', 'final_folder', copy_function=shutil.move, dirs_exist_ok=True)
'final_folder'
>>> os.listdir('staging_folder')
[]
>>> os.listdir('final_folder')
['file1', 'file2', 'file3']
Upvotes: 5
Reputation: 575
It turns out the path was not correct because it contains \t which was misinterpreted.
I ended up using shutil.move + shutil.copy22
for i in os.listdir(staging_folder):
if not os.path.exists(final_folder):
shutil.move(os.path.join(staging_folder, i), final_folder)
else:
shutil.copy2(os.path.join(staging_folder, i), final_folder)
and then emptify the old folder:
def emptify_staging(self, folder):
for the_file in os.listdir(folder):
file_path = os.path.join(folder, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
# elif os.path.isdir(file_path): shutil.rmtree(file_path)
except Exception as e:
print(e)
Upvotes: 2
Reputation: 82765
You can use the os.listdir
and then move each file to the required destination.
Ex:
import shutil
import os
for i in os.listdir(staging_folder):
shutil.move(os.path.join(staging_folder, i), final_folder)
Upvotes: 0