Python >> Tutoriel Python >  >> Python

Explorer le module OS de Python

Les modules Python OS permettent aux utilisateurs d'interagir avec les fichiers et les répertoires. Python utilise de nombreuses fonctions ou méthodes pour travailler avec des fichiers ou des répertoires. Cependant, dans cet article, nous allons considérer trois (3) fonctions essentielles. Maintenant, plongeons-y directement !

Python – os.rename()

Système d'exploitation Python rename() La méthode file renomme un fichier ou un répertoire. Cette méthode fonctionne en passant deux arguments nommés; src (Source) et dst (Destination).

Syntaxe :

os.rename(src, dst)

Paramètres :

  • Source :  Il s'agit d'un objet semblable à un chemin qui représente un chemin d'accès au système de fichiers. Il s'agit du chemin du fichier source cible à renommer.
  • Destination :  Il s'agit d'un objet semblable à un chemin qui représente un chemin d'accès au système de fichiers.

Type de retour :  Le os.rename() la méthode ne renvoie aucune valeur.

Code 1 : Comment le os.rename() la fonction fonctionne

# These codes explain the os.rename() method  
  
# how to import os module  
import os 
  
  
# Source file path 
source = 'Finx/ster.txt'
  
# destination file path 
dest = 'Finx/newster.txt'
  
  
# Using os.rename()method, rename the source path to destination path 
os.rename(source, dest) 
print("Source path successfully renamed to destination path.")

Sortie :

Source path successfully renamed to destination path

Code n° 2 : Comment traiter les erreurs probables 

# These codes explain the os.rename() method
  
# how to import os module 
import os 
  
  
# Source file path 
source = './Finx/ster.txt'
  
# destination file path 
dest = './finx/dir'
  
  
# using os.rename()method, attempt renaming src path to dst path
  
try : 
    os.rename(source, dest) 
    print("Source path successfully renamed to destination path.") 
  
# If Source is a file  
# but destination is a directory 
except IsADirectoryError: 
    print("Source is file, but destination is directory.")   
# If source is a directory 
# but destination is a file 
except NotADirectoryError: 
    print("Source is directory, but destination is file.") 
# For permission related errors 
except PermissionError: 
    print("Operation not permitted.") 
  
# For other errors 
except OSError as error: 
    print(error)

Sortie :

Source is file, but destination is directory

Créer un répertoire en Python

Le module Python OS utilise plusieurs méthodes pour créer un répertoire. Ce sont :

  • os.mkdir()
  • os.makedirs()

Utiliser os.mkdir()

Python utilise le os.mkdir() méthode pour créer un répertoire appelé "chemin" avec le mode numérique spécifié. Si le répertoire à créer existe déjà, os.mkdir() renvoie FileExistsError message dans une telle situation.

Syntaxe :

os.mkdir() et en facultatif cas, l'extension - "(path, mode =0o777, *, dir_fd =None)" - peut être ajoutée à la syntaxe.

Paramètre :

  • Chemin : Il s'agit d'un objet semblable à un chemin qui représente un chemin de système de fichiers. Cet objet semblable à un chemin est soit une chaîne, soit un objet bytes.
  • Mode (facultatif) :  Il s'agit d'une valeur entière qui représente le mode du répertoire à créer. Si ce paramètre est manquant, alors la valeur par défaut :Oo777 est appliquée.
  • répertoire_fd (facultatif) :  Il s'agit d'un descripteur de fichier faisant référence à un répertoire. Il est important de noter que la valeur par défaut de ce paramètre est "Aucun". Veuillez noter que dir_fd est ignoré, si le chemin spécifié est absolu. Veuillez noter que  le ‘*’ dans la liste des paramètres indique que tous les paramètres suivants (dans ce cas ‘dir_fd’ ) sont uniquement des mots clés.

Type de retour : Veuillez noter que cette méthode ne renvoie aucune valeur

Exemple #1 : Comment créer un fichier ou un répertoire à l'aide du os.mkdir() méthode

# These codes explain os.mkdir()method 
  
# importing os module 
import os 
  
# Directory 
directory = "Finx"
  
# Parent Directory path 
parent_dir = "D:/Pycharm projects/"
  
# Path 
path = os.path.join(parent_dir, directory) 
  
# Create the directory 
# 'Finxter' in 
# '/home / User / Documents' 
os.mkdir(path) 
print("Directory '% s' created" % directory) 
  
# Directory 
directory = "Finxter"
  
# Parent Directory path 
parent_dir = "D:/Pycharm projects"
  
# mode 
mode = 0o666
  
# Path 
path = os.path.join(parent_dir, directory) 
  
# Create the directory 
# 'Finx' in 
# '/home / User / Documents' 
# with mode 0o666 
os.mkdir(path, mode) 
print("Directory '% s' created" % directory)

Sortie :

Directory 'Finx' created
Directory 'Finxter' created

Exemple 2 : Erreurs probables lors de l'utilisation du os.mkdir() méthode.

# These codes explain os.mkdir() method   
      
# importing os module   
import os  
    
# Directory  
directory = "Finx"
    
# Parent Directory path  
parent_dir = "D:/Pycharm projects/"
# Path  
path = os.path.join(parent_dir, directory)      
# Create the directory  
# 'Finx' in  
# '/home / User / Documents'  
os.mkdir(path)  
print("Directory '% s' created" % directory)  
    
# if directory / file that   
# is to be created already  
# exists then 'FileExistsError' message  
# will be returned by os.mkdir() method  
    
# Similarly, if the specified path  
# is invalid 'FileNotFoundError' Error  
# will be flagged

Sortie :

Traceback (most recent call last):
     File “gfg.py”, line 18, in
         Os.mkdir(path)
FileExistsError: [WinError 183] Cannot create a file when that file /
		      /already exists: ‘D:/Pycharm projects/Finx’

Exemple #3 : Comment traiter les erreurs probables lors de l'utilisation de os.mkdir() méthode.

# These codes explain os.mkdir()method   
      
# importing os module   
import os  
    
# path  
path = 'D:/Pycharm projects / Finx'
    
# Create the directory  
# 'finx' in  
# '/home / User / Documents'  
try:  
    os.mkdir(path)  
except OSError as error:  
    print(error)

Comment vérifier si un fichier ou un répertoire existe

Python est un langage de programmation populaire, polyvalent et avancé. Il est connu pour avoir de nombreuses fonctionnalités, et l'une de ces fonctionnalités est la possibilité de vérifier si un fichier ou un répertoire existe déjà ou non. Python effectue cette tâche à l'aide d'un module OS intégré .

Avec le module OS, Python fournit les fonctions nécessaires pour interagir avec le système d'exploitation. Le système d'exploitation fait partie des modules utilitaires standard de Python et ces modules offrent un moyen efficace d'utiliser les fonctionnalités dépendant du système d'exploitation. Le os.path module est un sous-module de Python, utilisé pour manipuler les noms de chemin communs.

Comment vérifier si un fichier existe déjà

The os.path.isfile() La méthode vérifie si le chemin spécifié est un fichier existant ou non. Veuillez noter que os.path.isfile() suit les liens symboliques.

Syntaxe :  os.path.isfile(path)

Paramètre  :

  • Chemin : Il s'agit d'un objet semblable à un chemin qui représente un chemin de système de fichiers. Cet objet semblable à un chemin est soit une chaîne, soit un objet bytes.

Type de retour :  Cette méthode renvoie une valeur booléenne. il renvoie ‘True’ si le chemin spécifié est un fichier existant. Sinon, il renvoie ‘False’ .

Exemple :

# These codes explain os.path.isfile() method   
      
# importing os module   
import os  
    
# Path  
path = 'D:/Pycharm projects/Finx/vos/quiz_vos.txt'
    
# Check whether the   
# specified path is   
# an existing file  
isFile = os.path.isfile(path)  
print(isFile) 
    
    
# Path  
path = 'D:/Pycharm projects/Finx/vos/'    
# Check whether the   
# specified path is   
# an existing file  
isFile = os.path.isfile(path)  
print(isFile)

Sortie :

True
False

Comment vérifier si un répertoire existe

Python utilise le os.path.isdir() méthode pour vérifier si un chemin spécifié est un répertoire existant ou non. Cette méthode suit un lien symbolique, ce qui signifie que si le chemin spécifié est un lien symbolique pointant vers un répertoire, alors le processus renvoie ‘True’ .

Syntaxe :  os.path.isdir(path)

Paramètre :

  • Chemin : Il s'agit d'un objet semblable à un chemin qui représente un chemin de système de fichiers.

Type de retour :  Cette méthode renvoie une valeur booléenne. Cette méthode renvoie ‘True’ si le chemin spécifié est un répertoire existant. Sinon, il renvoie ‘False’ .

Exemple #1 : Comment utiliser le os.path.isdir() méthode.

# These codes explain os.path.isdir() method   
      
# importing os.path module   
import os.path  
    
# Path  
path = 'D:/Pycharm projects/Finx/vos/quiz_vos.txt'
    
# Check whether the   
# specified path is an  
# existing directory or not  
isdir = os.path.isdir(path)  
print(isdir)  

# Path  
path = 'D:/Pycharm projects/Finx/vos/'
    
# Check whether the   
# specified path is an  
# existing directory or not  
isdir = os.path.isdir(path)  
print(isdir) 

Sortie :

False
True

Exemple 2 : Que se passe-t-il si le chemin spécifié est un lien symbolique ?

# These codes explain os.path.isdir() method.   
      
# importing os.path module.   
import os.path  
    
    
# Create a directory(in current working directory).  
dirname = "Finx"
os.mkdir(dirname)  
    
# Create a symbolic link pointing to the above directory.  
symlink_path = "D:/Pycharm projects/Finx/vos/"
os.symlink(dirname, symlink_path)  
        
path = dirname  
    
# Investigate if the specified path is an existing directory or not.  
isdir = os.path.isdir(path)  
print(isdir)  
    
path = symlink_path  
    
# Check whether the specified path - a symbolic link - is an  
# existing directory or not.  
isdir = os.path.isdir(path)  
print(isdir)

Sortie :

True
True

Comment vérifier si un fichier ou un répertoire existe

Python utilise le os.path.exists() méthode pour vérifier si un chemin spécifié existe ou non. Cette méthode vérifie également si le chemin donné fait référence à un descripteur de fichier ouvert ou non. La méthode vérifie si un fichier ou un répertoire existe.

Syntaxe :  os.path.exists(path)

Paramètre :
Chemin :
C'est un objet semblable à un chemin qui représente un chemin de système de fichiers. Cet objet semblable à un chemin est soit une chaîne, soit un objet bytes.

Type de retour : Cette méthode renvoie une valeur booléenne. The os.path.exists() la méthode renvoie "True", si le chemin existe. Sinon, il renvoie "Faux".

Exemple :

# These codes explain os.path.exists() method   
       
# importing os module   
import os  
     
# Path  
path = 'D:/Pycharm projects/Finx/vos/quiz_vos.txt'
     
# Find out if the specified path is an existing file.  
isExist = os.path.exists(path)  
print(isExist) 
         
# Path  
path = 'D:/Pycharm projects/Finx/vos/'
     
# Finally, check if the specified path is an existing file.  
isExist = os.path.exists(path)  
print(isExist)

Sortie :

True
True

Veuillez noter que même si le chemin existe, le os.path.exists() la fonction peut toujours retourner 'False', si l'exécution de os.stat() n'est pas autorisé.

Pour en savoir plus sur Python, devenez Finxter Scholar. Inscrivez-vous ici https://blog.finxter.com/email-academy/ maintenant !

Référence