J'ai ce code pour ouvrir un dossier avec ces répertoires. Certains d'entre eux ont l'extension html mais pas tous. Comment puis-je changer tous les fichiers de mes trois sous-répertoires qui n'ont pas d'extension html en .html?
from os import walk mypath = ("/directory/path/to/folder") f = [] for (dirpath,dirnames,filenames) in walk(mypath): f.extend(filenames) print(f)
4 Réponses :
Tout d'abord, écrivez un générateur de chemin d'image avec la fonction suivante:
paths = getimagepath("............................") for path in paths: if not path.endswith('.html'): os.rename(path,path+'.html')
Entrez le chemin de votre dossier dans la fonction. Ensuite, lancez une boucle for en vérifiant que le nom se termine par html, puis changez le nom avec os.rename
import os def getimagepath(root_path): for root,dirs,filenames in os.walk(root_path): for filename in filenames: yield(os.path.join(root,filename))
Peut-être mieux avec sinon path.endswith ('. Html')
. Vérifiez également le .
ainsi vous obtenez un nom de fichier comme mynamehtml
ff = [] for (dirpath,dirnames,filenames) in os.walk(mypath): for f in filenames: if not f.endswith(".html"): #check if filename does not have html ext new_name = os.path.join(dirpath,f+".html") os.rename(os.path.join(dirpath,f),new_name) #rename the file ff.append(f+".html") else: ff.append(f) print(ff)
Appelez cette fonction avec votre chemin.
import os import os.path def ensure_html_suffix(top): for dirpath, _, filenames in os.walk(top): for filename in filenames: if not filename.endswith('.html'): src_path = os.path.join(dirpath, filename) os.rename(src_path, f'{src_path}.html')
Si vous utilisez Python 3.4 ou supérieur, envisagez d'utiliser pathlib .
Voici une solution à votre problème en utilisant cela:
from pathlib import Path mypath = Path('/directory/path/to/folder') for f in mypath.glob('*'): if f.is_file() and not f.suffix: f.rename(f.with_suffix('.html'))
Si vous devez également accéder aux sous-répertoires, vous pouvez utiliser le Path.glob ()
méthode à lister tous les répertoires de manière récursive, puis traitez chaque fichier de ce répertoire. Quelque chose comme ceci:
from pathlib import Path mypath = Path('/directory/path/to/folder') for dir in mypath.glob('**'): for f in dir.iterdir(): if f.is_file() and not f.suffix: f.rename(f.with_suffix('.html'))
Et voici une autre façon de parcourir tous les répertoires et de traiter tous les fichiers:
from pathlib import Path mypath = Path('/directory/path/to/folder') for f in mypath.iterdir(): if f.is_file() and not f.suffix: f.rename(f.with_suffix('.html'))
Utilisation de Path.glob ()
avec deux astérisques listera tous les sous-répertoires et avec un seul astérisque, il listera tout sur ce chemin.
J'espère que cela aide.
L'une des réponses vous a-t-elle aidé? Si tel est le cas, veuillez en marquer un comme accepté. De cette façon, vous aiderez d'autres personnes avec la même question.