KieranF
KieranF

Reputation: 79

How to move files with a specified extension to a new folder in Python

I am trying to move files within a folder to another folder whilst only moving files with the extensions .bmp.

I am using the shutil.move() method and it works when I don't specify file types but once I do it stops working. I have tried to debug it but cant figure out why my code isn't working. I dont get any tracebacks, nothing happens.

 import time
 import os
 import shutil
 from datetime import datetime

 today = datetime.now()

 src = "."
 dst = ('C:\Python\Image Compressor\File Saving\Archive\BDB040803_St14_' + 
 today.strftime('%d_%m_%Y'))
 files = os.listdir(src)
 for file in src:
     if file.endswith(".bmp"):
          shutil.move(os.path.join(src,file), os.path.join(dst,file))

Upvotes: 1

Views: 1893

Answers (3)

Timus
Timus

Reputation: 11321

In case you're interested in an alternative approach (yours isn't bad, this isn't meant as criticism).

You could use pathlib:

from pathlib import Path
from datetime import date

src = Path()
dst = Path(
    r"C:\Python\Image Compressor\FileSaving\Archive\BDB040803_St14_"
    + date.today().strftime("%d_%m_%Y")
)
for file in src.glob("*.bmp"):
    file.replace(dst / file.name)

.glob allows you to fetch path/file-names that match patterns. The pattern structures aren't as powerful as regex, but can still be pretty helpful. You could also use the glob module directly.

.replace takes over shutil.move's job.

Upvotes: 1

KieranF
KieranF

Reputation: 79

Okay so I have finally solved my problem. I will post my code here for a reference for anyone else who runs into this problem. @siloob thank you for your input, you were correct with your correction but I still had tracebacks after this so I had a few more changes to make.

I needed my bmp files to transfer and not my .py files so I added an if statement with a continue to skip over any files with .py. This solved my problem and only transferred the bmp files.

 import time
 import os
 import shutil
 from datetime import datetime

 today = datetime.now()

 src = "."
 dst = ('C:\Python\Image Compressor\File Saving\Archive\BDB040803_St14_' + 
 today.strftime('%d_%m_%Y'))
 files = os.listdir(src)
 for file in files:
     if file.endswith(".py"):
         continue
     else:
         shutil.move(os.path.join(src,file), os.path.join(dst,file))

Upvotes: 0

siloob
siloob

Reputation: 86

Replace src by files in line:

 for file in src:

Upvotes: 2

Related Questions