Skip to content

Python file open modes

In Python, the built-in open() function is the standard mechanism for file handling. It accepts two primary arguments: the file path (or name) and the access mode.^[400-devops-09-scripting-language-python-introduction-part-2files-readme.md]

Access Modes

The access mode is a string that defines the intended operations on the file (reading, writing, or creating).^[400-devops-09-scripting-language-python-introduction-part-2files-readme.md] Common modes include:

  • "r" (Read): The default mode. Opens a file for reading. If the file does not exist, the operation raises a FileNotFoundError.^[400-devops-09-scripting-language-python-introduction-part-2files-readme.md]
  • "a" (Append): Opens a file for appending data. If the file does not exist, it will be created automatically.^[400-devops-09-scripting-language-python-introduction-part-2files-readme.md]
  • "w" (Write): Opens a file for writing data. If the file does not exist, it will be created.^[400-devops-09-scripting-language-python-introduction-part-2files-readme.md]
  • "x" (Create): Creates the specified file. This mode will return an error if the file already exists.^[400-devops-09-scripting-language-python-introduction-part-2files-readme.md]

File Object Operations

Once a file is opened successfully, it returns a file object (often assigned to a variable like f).^[400-devops-09-scripting-language-python-introduction-part-2files-readme.md]

To read the entire content of the file at once, the read() method can be called on the file object^[400-devops-09-scripting-language-python-introduction-part-2files-readme.md].

content = f.read()

It is good practice to close the file once operations are complete to free up system resources^[400-devops-09-scripting-language-python-introduction-part-2files-readme.md].

f.close()
  • [[Python]]
  • [[CSV handling]]
  • [[File system operations]]

Sources