Renomeador de arquivo recursivo - o script python muito útil para de funcionar após a atualização do Python (Pyt2 para Pyt3). Alguém pode encontrar e corrigir o problema, por favor? Obrigado!
Exemplo, esses arquivos:
'Linux příručka českého uživatele.pdf' 'LINUXTERO příkazy které se vždy hodí.pdf' 'Práce s archívy příkazové řádka.pdf' 'Rekurzivní grep.txt'
altere para esses arquivos:
linux_prirucka_ceskeho_uzivatele.pdf' linuxtero_prikazy_ktere_se_vzdy_hodi.pdf prace_s_archivy_prikazove_radka.pdf rekurzivni_grep.txt
O programador é tcheco, então tenho que traduzir via Google para inglês...
Quando inicio o script, recebi uma massagem com falha da seguinte forma:
linq@legion5:~/test-renamer/ask_stackexchange_folder$ vycisti.py Arquivo "/home/linq/bin/vycisti.py", linha 62 print "Aviso: '%s' ainda não é um nome válido" % fileName ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^ SyntaxError: parênteses ausentes na chamada para 'print'. Será que quis dizer print(...)?
Aqui está o roteiro:
#!/usr/bin/python
# -*- coding: utf-8
'''Renames all files and directories in the current directory to
to have some culture. It also works recursively in nested ones
directories. The changes are as follows:
Czech characters -> English
cancels all dashes and spaces at the beginning of the name (damn, what kind
the names make up would deserve a few slaps)
special characters are replaced by '_', I take the hyphen at mercy, but not at the beginning
the (unnecessary) '_' around the hyphen is discarded
multiple '_'s are replaced by a single occurrence
everything will be converted to lowercase
The result should be a title where there are only letters, underscores,
numbers, periods and dashes (but not at the beginning).
It writes exactly what it does to standard output
Usage: vycisti.py [ > logfile ]
'''
import re
import os
import sys
import unicodedata
class RenameFiles:
def __init__(self):
if os.environ.get('OS','') == 'Windows_NT':
self.locale = "cp1250"
else: #probably linux
local = os.environ.get('LANG', '')
if '.' in local: #Fedora way
self.locale = local.split('.')[1]
else: #Debian
self.locale = 'iso-8859-2'
def cleanString(self, what):
'''Gets rid of letters which are not in English alphabet'''
assert type(what) == unicode
normalized = unicodedata.normalize('NFKD', what)
output = ''
for c in normalized:
if not unicodedata.combining(c):
output += c
return output
def cleanName(self, fileName):
'''Convert the givne string into a form which is suitable for a file name'''
assert type(fileName) == str
fileName = self.cleanString(fileName.decode(self.locale))
fileName = re.sub("^[-\ ]+", "", fileName) #delete space or dash at the beginning
invalid_stuff = re.compile(r"[^a-zA-Z0-9_\.-]+") #forbidden characters (non-alfanumerical)
fileName = invalid_stuff.sub("_", fileName.strip()) #replace invalid stuff and spaces by _,
fileName = re.sub("_+", "_", fileName) #squeeze continuous underscores to one _
fileName = re.sub("-+", "-", fileName) #squeeze continuous dashes to one _
fileName = re.sub("_*-_*", "-", fileName) #removes useless '_' round the dash
fileName = re.sub("_*\._*", ".", fileName) #removes useless '_' round the dot
fileName = re.sub("-*\.-*", ".", fileName) #removes useless '-' round the dot
fileName = fileName.lower() #lower case
valid_name=re.compile(r"^[a-z0-9_\.][a-z0-9_\.-]+$") #regular expression for feasible name
if not valid_name.match(fileName):
print "Warning: '%s' is still not valid name" % fileName
return fileName.encode(self.locale)
def renameFile(self, dir, fileName):
'''Public: Renames the file fileName in the directory'''
assert type(fileName) == str
assert type(dir) == str
try:
new = self.cleanName(fileName)
except:
print "Problem: %s %s " % (fileName, sys.exc_info()[0] )
new = ""
if (new != "" and new != fileName):
print "Renaming %s: %s -> %s" % (dir, fileName, new) #kontrolní výpis
os.rename(dir+os.sep+fileName, dir+os.sep+'tmp')
os.rename(dir+os.sep+'tmp', dir+os.sep+new)
return
def process_dir(self, dir):
"""process all files in the folder"""
assert type(dir) == str
for f in os.listdir(dir):
fileName = dir + os.sep + f
if os.path.isdir(fileName) and os.access(fileName, os.W_OK): #if it is directory
self.process_dir(fileName) #process the elements in the directory
self.renameFile(dir, f) #rename the directory itself
else:
self.renameFile(dir, f) #if it is a file
return
if __name__=='__main__':
renamer = RenameFiles()
renamer.process_dir('.')
Como dito nos comentários, o Python2 está obsoleto. Há outras ferramentas que podem fazer o truque ...
Usando Perl
rename
:¹
zsh
padrão, o bash precisashopt -s globstar
antes do comando ser executado.Precisa
sudo apt install rename libtext-unidecode-perl
de pacotes (Debian*/Ubuntu/Mint...
).Remova
-n
(também conhecido comodry-run
) quando a saída parecer satisfatória.Saída
Python 2 agora é uma linguagem morta (pôr do sol em 1º de janeiro de 2020)
Houve muito tempo em que as pessoas escreveram códigos compatíveis com python 2 e 3. Portanto, eles são semelhantes, mas as diferenças permanecem.
Talvez o mais conhecido seja o mencionado no erro. As instruções "print" agora precisam de colchetes:
imprimir "foo"
É agora
print("foo")