I want to move all text files from one folder to another folder using Python. I found this code:
import os, shutil, glob dst = '/path/to/dir/Caches/com.apple.Safari/WebKitCache/Version\ 4/Blobs ' try: os.makedirs(/path/to/dir/Tumblr/Uploads) # create destination directory, if needed (similar to mkdir -p) except OSError: # The directory already existed, nothing to do pass for txt_file in glob.iglob('*.txt'): shutil.copy2(txt_file, dst)
I would want it to move all the files in the Blob
folder. I am not getting an error, but it is also not moving the files.
The shutil. copytree() method recursively copies an entire directory tree rooted at source (src) to the destination directory. It is used to recursively copy a file from one location to another. The destination should not be an existing directory.
You can move a file or folder from one folder to another by dragging it from its current location and dropping it into the destination folder, just as you would with a file on your desktop. Folder Tree: Right-click the file or folder you want, and from the menu that displays click Move or Copy.
Firstly import shutil module, and store the path of the source directory and path of the destination directory. Make a list of all files in the source directory using listdir() method in the os module. Now move all the files from the list one by one using shutil. move() method.
Try this:
import shutil import os source_dir = '/path/to/source_folder' target_dir = '/path/to/dest_folder' file_names = os.listdir(source_dir) for file_name in file_names: shutil.move(os.path.join(source_dir, file_name), target_dir)
suprised this doesn't have an answer using pathilib which was introduced in python 3.4
+
additionally, shutil updated in python 3.6
to accept a pathlib object more details in this PEP-0519
from pathlib import Path src_path = '\tmp\files_to_move' for each_file in Path(src_path).glob('*.*'): # grabs all files trg_path = each_file.parent.parent # gets the parent of the folder each_file.rename(trg_path.joinpath(each_file.name)) # moves to parent folder.
from pathlib import Path import shutil src_path = '\tmp\files_to_move' trg_path = '\tmp' for src_file in Path(src_path).glob('*.*'): shutil.copy(src_file, trg_path)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With