Languages
[Edit]
EN

Python - open file

0 points
Created by:
eyllanesc
277

In this article, we would like to show you how to open the file for working with it in Python.

Quick solution:

file = open("example.txt")
file = open("D:\\myfiles\example.txt", "r")

 

The open() file is one of the key functions for working with files in Python.

It takes two parameters - file name and mode.

There are four available modes for opening a file:

  • r - read - default value, opens a file for reading, throws an error if the file doesn't exist,
  • w - write - opens a file for writing, creates the file if it doesn't exist,
  • a - append - opens a file for appending at the end of it, creates the file if it doesn't exist,
  • x - create - creates the file, throws an error if the file exists.

additionally, there is a parameter that specifies if the file should be handled as binary or text mode:

  • t - text mode (default value),
  • b - binary mode (e.g. for images).

 

Practical examples

Example 1

In this example, we open a text file for reading.

file = open("example.txt")

or

file = open("example.txt", "rt")

Note:

To open a file for reading it is enough to specify only the file name.

Example 2

In this example, we show how to open a file in a different location.

file = open("C:\\file\\example.txt", "rt")

Python - file operations

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join