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 like it to move all the files in the Blob folder. I do not receive an error message, but it also does not move files.

+5
source share
4 answers

Try it.

 import shutil import os source = '/path/to/source_folder' dest1 = '/path/to/dest_folder' files = os.listdir(source) for f in files: shutil.move(source+f, dest1) 
+8
source

Copying the ".txt" file from one folder to another is very simple and the question contains logic. Only the missing part replaces the correct information, as shown below:

 import os, shutil, glob src_fldr = r"Source Folder/Directory path"; ## Edit this dst_fldr = "Destiantion Folder/Directory path"; ## Edit this try: os.makedirs(dst_fldr); ## it creates the destination folder except: print "Folder already exist or some error"; 

below the line of code will copy the file with * .txt extension files from src_fldr to dst_fldr

 for txt_file in glob.glob(src_fldr+"\\*.txt"): shutil.copy2(txt_file, dst_fldr); 
+3
source

That should do the trick. Also read the shutil module documentation to select a function that suits your needs (shutil.copy (), shutil.copy2 (), shutil.copyfile (), or shutil.move ()).

 import glob, os, shutil source_dir = '/path/to/dir/with/files' #Path where your files are at the moment dst = '/path/to/dir/for/new/files' #Path you want to move your files to files = glob.iglob(os.path.join(source_dir, "*.txt")) for file in files: if os.path.isfile(file): shutil.copy2(file, dst) 
+1
source

Please take a look at the implementation of the copytree function, which:

  • List of directory files with:

    names = os.listdir(src)

  • Copy files using:

    for name in names: srcname = os.path.join(src, name) dstname = os.path.join(dst, name) copy2(srcname, dstname)

Getting dstname is not necessary because if the destination parameter specifies a directory, the file will be copied to dst using the base file name from srcname.

Replace copy2 with move.

0
source

Source: https://habr.com/ru/post/1263248/


All Articles