English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Python

Contrôle de flux Python

Fonctions en Python

Types de données en Python

Opérations de fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Utilisation et exemple de open() en Python

Python built-in functions

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)

Paramètres de open()

  • 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 :

    ModeDescription
    '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

open() return value

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.

Example1: How to open a file in Python?

# 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.

Example2: Provides open() mode

# 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

Python built-in functions