Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving all files from one directory to another using Python

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.

like image 942
malina Avatar asked Jan 24 '17 11:01

malina


People also ask

How do you copy all the files in a directory to another directory in Python?

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.

How do you move all files from a directory to another?

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.

How do I move a folder to another folder in Python?

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.


2 Answers

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) 
like image 88
Shivkumar kondi Avatar answered Oct 14 '22 13:10

Shivkumar kondi


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

Pathlib

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. 

Pathlib & shutil to copy files.

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) 
like image 23
Umar.H Avatar answered Oct 14 '22 15:10

Umar.H