English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
La fonction open() ouvre un fichier et retourne l'objet de fichier correspondant.
La syntaxe de open() est :
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
file -Objet de chemin similaire (représentant le chemin du système de fichiers)
mode(Optional)-Le mode d'ouverture du fichier. Si non spécifié, le mode par défaut est 'r' (ouvrir en mode texte). Les modes de fichier disponibles sont :
Mode | Description |
---|---|
'r' | Ouvrir le fichier pour la lecture. (par défaut) |
'w' | Ouvrir le fichier pour l'écriture. S'il n'existe pas, créer un nouveau fichier, ou si il existe, le raccourcir. |
'x' | Ouvrir le fichier pour la création en exclusivité. Si le fichier existe déjà, l'opération échoue. |
'a' | Open to append at the end of the file without truncating. If it does not exist, a new file will be created. |
't' | Open in text mode. (Default) |
'b' | Open in binary mode. |
'+' | Open the file for update (read and write) |
buffering (Optional)-Used to set buffer strategy
encoding (Optional)-Encoding format
errors (Optional)-String, specify how to handle encoding/Decoding error
newline(Optional) -How to work in newline mode (available values: None, ' ', '\n', 'r', and '\r\n')
closefd(Optional)-Must be True (default); if another value is specified, an exception will be raised
opener(Optional)-Custom opener; must return an open file descriptor
The open() function returns a file object that can be used to read, write, and modify the file.
If the file is not found, it will raise a FileNotFoundError exception.
# Open the test.txt file in the current directory f = open("test.txt") # Specify the full path f = open("C:")/Python33/README.txt")
Since the mode is omitted, the file will be opened in 'r' mode. Open for reading.
# Open the file in read mode f = open("path_to_file", mode='r') # Open the file in write mode f = open("path_to_file", mode = 'w') # Open the file in append mode f = open("path_to_file", mode = 'a')
The default encoding of Python is ASCII. You can easily change it by passing the encoding parameter.
f = open("path_to_file", mode = 'r', encoding='utf-8)
Recommended reading: Python file input/Output