For web-uploading of Cyrillic-named images, I've written the script below:
#!/usr/bin/python
# coding=utf-8
import os
import argparse
import shutil
class Error: pass
class FolderError(Error): pass
def copytranstree (src, dst):
names = os.listdir( src )
try:
os.makedirs( dst )
except WindowsError:
pass
errors = []
for name in names:
srcname = os.path.join( src, name )
dstname = os.path.join( dst, ''.join([translit.get(x, x) for x in name.decode( input_parametres.encoding ).lower()]).encode( input_parametres.encoding ) )
try:
if os.path.isdir( srcname ):
copytranstree( srcname, dstname )
else:
shutil.copy2( srcname, dstname )
except (IOError, os.error), why:
errors.append( ( srcname, dstname, str( why ) ))
except Error, err:
errors.extend( err.args[0] )
try:
shutil.copystat( src, dst )
except WindowsError:
pass
except OSError, why:
errors.extend( (src, dst, str(why) ) )
if errors:
raise Error( errors )
parser = argparse.ArgumentParser(description='Copy directory tree with transliterated pathnames')
parser.add_argument('-e','--encoding', help='File system encoding', default='utf-8')
parser.add_argument('-s','--src', help='Source folder name', default='./' )
parser.add_argument('-d','--dst', help='Destination folder name', default='./')
input_parametres = parser.parse_args()
translit = dict(zip(u"абвгдеёзийклмнопрстуфхьъ", "abvgdeeziyklmnoprstufh'~"))
translit.update({u'ц': 'tz', u'ч': 'ch', u'ш': 'sh', u'ы': 'yi',
u'э': 'ye', u'ю': 'ju', u'я': 'ja', u' ': '_'})
src = os.path.abspath( input_parametres.src )
dst = os.path.abspath( input_parametres.dst )
if not os.path.exists( dst ):
dstname = ''.join([translit.get(x, x) for x in dst.decode( input_parametres.encoding ).lower()]).encode( input_parametres.encoding ).lower()
os.makedirs( dstname )
dst = os.path.abspath( dstname )
if not os.path.exists( src ) or os.path.isfile( dst ):
raise FolderError()
copytranstree( src, dst )
The script transliterates and copies a tree of files from a source folder to destination, considering encoding passed to the script (UTF for Ubuntu, CP121 for Windows).
Any ideas for common improvement of structure for Linux OS?