Python script create folders from filename

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Python script create folders from filename



Searching a python script thats move files to directions created based on the filenames.



Ex.

Filename is ARC20180810185310.jpg

Move that file to:
2018>08


ARC20180810185310.jpg


2018>08



Filename is ARC20180910185310.jpg

Move that file to:
2018>09


ARC20180910185310.jpg


2018>09





What have you tried so far?
– ukemi
Aug 10 at 10:01




3 Answers
3



It's good to try something yourself first, the ask on SO - you learn much more that way.



I would try:


import os
from shutil import copyfile
folder_path = '*folder path*'
os.chdir(folder_path)
for file in os.listdir(folder_path)
year = file[3:7]
month = file[7:9]
final_path = folder_path + '/' + year + '>' + month + '/' + file + .jpg'
copyfile(file, final_path)



Just replace the paths in ** with whatever you need.



This way you slice the file name and get year and month from it (characters from 3 to 6 and 7,8), then copyfile to a path consisting of both year and month that you sliced.



Just replace the srcDir and dstDir, you will get your file.jpg moved, if you use MoveFile(srcDir, dstDir, resuisive=True), you will move the file.jpg in the sub-dir of the srcDir too.


from __future__ import print_function
import os, re, shutil

class MoveFile(object):
def __init__(self, srcDir, dstDir, recursive=False, flag='.JPG'):
self.srcDir = srcDir
self.dstDir = dstDir
self.recursive = recursive
self.flag = flag
self.duplicateFileName =
self.badFileName =
self.jpgFile =
self.srcDirDict =

def findAllJPG(self):
# recursively find file
if self.recursive == False:
for item in os.listdir(self.srcDir):
if os.path.isfile(os.path.join(self.srcDir,item)) and
os.path.splitext(item)[-1] == self.flag.lower():
self.jpgFile.append(item)
else:
for root, dirs, files in os.walk(self.srcDir):
for item in files:
if os.path.splitext(item)[-1] == self.flag.lower():
self.jpgFile.append(item)
self.srcDirDict[item] = root

if not self.jpgFile:
print('NOT FIND ANY JPG FILE!')
return self.jpgFile

def parse(self, text):
try:
pat =re.compile('[a-zA-Z]+([d]+)')
match = pat.match(text)
data = match.group(1)
fileName = data[:4]+'-'+data[4:6]
except TypeError:
self.badFileName.append(text)
fileName = None
return fileName

def move(self, text):
try:
fileName = self.parse(text)
if fileName == None: return
if not os.path.isdir(os.path.join(self.dstDir, fileName)):
os.mkdir(os.path.join(self.dstDir,fileName))

srcPath= os.path.join(self.srcDirDict[text], text)
dstDir = os.path.join(self.dstDir, fileName)
shutil.move(srcPath, dstDir)
except:
self.duplicateFileName.append(text)
raise

@staticmethod
def decC(dir):
return os.path.join(self.srcDir,dir)

def run(self):
try:
if not os.path.isdir(self.dstDir):
os.mkdir(self.dstDir)
for text in self.findAllJPG():
self.move(text)
print('MOVE SUCCESSFUL!')
except:
raise

srcDir = r'C:UsersAdministratorDesktop2'
dstDir = r'C:UsersAdministratorDesktop3'
fmv = MoveFile(srcDir, dstDir, recursive = False)

fmv.run()



First of all you will need glob.glob() function to find all files in given directory:


files = glob.glob('ARC*.jpg')



Then you will need to extract some parts of filename:


year = filename[3:7]
month = filename[7:9]



Use os.makedirs() with exist_ok=True and create the dirs:


os.makedirs(os.path.join(BASE_DIR, year, month))



Then use shutil.move to move file to specific directory


shutil.move(filename, os.path.join(BASE_DIR, year, month, filename))



Finally you will get something like this:


import glob
import os.path
import shutil

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

files = glob.glob('ARC*.jpg')
for filename in files:
year = filename[3:7]
month = filename[7:9]
try:
os.makedirs(os.path.join(BASE_DIR, year, month))
except OSError:
pass
shutil.move(filename, os.path.join(BASE_DIR, year, month, filename))





have a look at year and month in the beginning of your post, seems like there's a typo and you take wrong values, like 0180 instead of 2018. In the final version it's fine though :)
– Piotrek
Aug 10 at 10:40


year


month


0180


2018





Thanks but goy a problem that in Python 2.7.xxx "exist_ok=True" not working.
– Hans Pettersson Nyholm
Aug 10 at 12:08







By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard