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.
Copying the ".txt" file from one folder to another is very simple and question contains the logic. Only missing part is substituting with right information as below:
below lines of code will copy the file with *.txt extension files from src_fldr to dst_fldr
Please, take a look at implementation of the copytree function which:
List directory files with:
names = os.listdir(src)
Copy files with:
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 destination parameter specifies a directory, the file will be copied into dst using the base filename from srcname.
Replace copy2 by move.
This should do the trick. Also read the documentation of the shutil module to choose the function that fits your needs (shutil.copy(), shutil.copy2(), shutil.copyfile() or shutil.move()).
Try this..