×

How to open a file in python

Opening a File in Python

Python is a user-friendly programming language that makes almost every concept easy. It provides many inbuilt functions in its libraries to work with files. Using these functions, we can work with normal text files as well as complex binary files.

Binary files are the executable files made of only 0’s and 1’s. Any Python user can work with these files even though these files are not user- understandable. Normal text files are those we edit in text editors like notepad.

Important points:

In text files, by default, every line is terminated with a new line character (\n). This special character is called the EOL – End of Line character.

In binary files, there is no such termination available.

To work with any file – to read from it or write in it, we need to open it. In Python, we have almost 6 access modes – the state in which the file will be opened and we have a function to open a file. We will discuss this in detail in this article.

Function: open ()

Syntax:

Object = open (“File name”, ‘mode’, encoding = ‘’)

  • File name:  represents the name of the file that we want to open in string format.

Note: While opening a file, we need to make sure that the Python program script we are writing and the file we want to open through it must be in the same location/ directory.

If they are in different locations, in the place of the file name, we have to specify the address of the file.

  • Encoding: It represents the character encoding for text files. When we try to open a text file, we need to specify the encoding because, in Python, the characters are converted into ASCII or Unicode or any other platform-dependent encodings. If that happens, the code will behave differently on different platforms. Hence, specifying the encoding is recommended.

In a windows system:

file = open ("Sample.txt", 'w')
print ("System encoding: ", file. encoding)
file. close ()

Output:

System encoding:  cp1252

Now, let us see the different opening modes available in Python:

At the foundation level, we have six modes of opening a file:

  1. r -> read-only
  2. w -> write only
  3. x -> exclusive file creation
  4. a -> append-only
  5. t -> text mode
  6. b -> binary mode

As the letters indicate,

  1. r opens a file only in read-mode; we cannot write or modify anything in the opened file. The file pointer points to the starting 0 index of the file.
    • It raises an Input-Output error if the file name we gave does not exist.
    • If we do not specify any mode in the mode parameter, this will be the default mode of opening the file.
  2. w opens a file for writing only. If the file already exists and there is some data in it, it will be truncated/ deleted, and it will open the empty file as we can't read in write mode.
    • If the file with the given name does not exist, it will by default create one and open it.
    • The file pointer points to the starting 0 index of the file.
  3. x creates and opens a file for writing-only if there is no file with the specified name already. It is used for exclusive file creation.
    • If a file already exists with the specified name, it raises a File Exists error.
  4. a is used to append a file from the end of an already written file without truncating it like in write mode.
    • If the file with the given name does not exist, it will by default create one and open it.
    • The file pointer will point to the end of the old file content.
  5. t opens the file in text format
  6. b opens the file in binary format.

Combinations

There is a special symbol + using which we can use combinations of these access modes. These combinations can be confusing, but every mode has its use in different scenarios. Here are the combinations we can try.

  1. r+: read and write
  2. w+: read and write

We can read and write in both modes, and the file pointer will be at the beginning in both modes.

 Now, what is the difference?

  1. In r+ mode, the file will be opened, and we can read the entire content from the file. The old content will be gone, and the content we write will overwrite the old content. It raises an Input-Output error if the file name we gave does not exist.
  2. In w+ mode, all the old content will be deleted, and an empty file will be opened. We cannot read the old content. We can write new content and read it. If the file with the given name does not exist, it will by default create one and open it.
  3. a+: read and write
    • The file pointer will be at the end of the old content, and we can write or append data from there and read it.
    • If the file with the given name does not exist, it will by default create one and open it.
  4. rb: To open a binary file in reading mode.
  5. wb: To open a binary file in write mode.
  6. ab: To open a binary file in append mode.
    By adding a b to the above operations, we can use the modes for binary files.
    The other modes for binary files are: rb+, wb+, ab+.

Example

Now, let us understand using examples: 

We created a text file “Sample” and wrote “Hi everyone!” in it. Now, let us open this file in different modes and see the functionalities:

Opening a File in Python
  • r mode:
file = open ("Sample.txt", 'r')
print (file. read ())
file. close ()

Output:

Hi everyone!
  • w mode:
file = open ("Sample.txt", 'w')
print (file. write ("Hi man!"))
file. close ()

Output:

7 (returns the length of the string we wrote)

File:

Opening a File in Python

The old content "Hi everyone!" is deleted, and "Hi man!" is written.

  • a mode:
file = open ("Sample.txt", 'a')
print (file. write ("Hi man!"))
file. close ()

Output:

7 (returns the length of the appended string)

File:

Opening a File in Python
  • r+ mode:
file = open ("Sample.txt", 'r+')
print (file. read ())
print (file. write ("Hello!"))
file. close ()

Output:

Hi man!Hi man!
6 (The length of the written string)

File:

Opening a File in Python

The file has “Hi man!Hi man!”. We used the read () function and read the content. Then, we used write () to write “Hello!” into the file.

  • w+ mode:
file = open ("Sample.txt", 'w+')
print (file. read ())
print (file. write ("Hello!"))
file. close ()

Output:

6 (The length of the string written)

File:

Opening a File in Python

The file has “Hi man!Hi man!Hello!". When we open the file in w+, the old content is deleted, and we read an empty file. Now, we wrote new content into the file "Hello!”.

Note: We can read the data we wrote into the file. But, if we read it after writing, we will get an empty string as the output as after writing, the file pointer will be at the end of the file. We need to use the seek () to get the pointer to the beginning.

file = open ("Sample.txt", 'w+')
print (file. read ())
print (file. write ("Hey man!"))
file. seek (0)
print (file. read ())
file. close ()

Output:

8
Hey man!
  • a+ mode:
file = open ("Sample.txt", 'a+')
print (file. read ())
print (file. write ("Hey man!"))
file. close ()

Output:

8

File:

Opening a File in Python

The pointer will be at the end of the file. Hence, when we read it, we got an empty string. We can use seek () to read it:

file = open ("Sample.txt", 'a+')
file. seek (0)
print (file. read ())
print (file. write ("Hey man!"))
file. seek (0)
print (file. read ())
file. close ()

Output:

Hello!
8
Hello!Hey man!

Working with binary files:

When we are handling binary files, the whole content will be in the form of 0's and 1's:

  1. If we want to write into it, we need to encode the data.
  2. If we want to read the data, we need to decode it; else, the data in the encoded file will be printed.

Let us take a simple example:

file = open ("Sample. bin", 'wb+')
string = "Hey there"
bstring = string. encode ("cp1252")
file. write (bstring)
file. seek (0)
binary = file. read ()
print (binary)
normal = binary. decode ("cp1252")
print (normal)

Output:

b'Hey there'
hey there

We opened a binary file in wb+ (read and write) format. We wanted to write a string “Hey there” into it. We used the encode () function to encode the data into system-understandable language and wrote it into the file. Now the file pointer will point to the end. We used the seek () function to get the pointer pointing to the beginning to read the content.

When we read the data, the encoded form of the string is printed. The b in the string represents binary. We decoded the encoding into the human-understandable format and printed it to get a normal string.

File opened using notepad:

Opening a File in Python

There are a lot more functions available to work with files in Python.


Related Topics

Python open() function

Python open() function The open() function in Python opens a file and returns a corresponding file object. If the file cannot be opened, an OSError is raised. Syntax open(file, mode='r', buffering=1, encoding=None, errors=None, newline=None, closefd=True, opener=None) Parameter file It represents the path and name of the file mode...

2 minutes read.

Python Set discard() method

Python Set discard() method The set.discard() method in Python removes a specified element from the set (if present). Syntax set.discard(value) Parameter value- This parameter represents the element to be removed from the set. Return None Example 1 # Python program explaining # the...

1 minute read.

Compound Interest GUI Calculator using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

6 minutes read.

Python Operators

Operators in Python programming An operator is a symbol that operates on one or more operands. An operand is a value or a variable on which we perform the operation....

5 minutes read.

Python memoryview() Function

Python memoryview() Function The memoryview() function in Python returns a memory view object from a specified object. Syntax memoryview(obj) Parameter obj: This parameter represents a Bytes object or a bytearray object. Return This function returns a “memory view” object...

1 minute read.

Python Data Visualization

In this tutorial, we will understand what data visualization means in python. Further, we will see different methods of visualizing data in python. Data visualization In a non-technical language, it is a...

4 minutes read.

How to Install Python In Windows

How To Install Python In Windows? Python is a language that every aspirant developer looks forward to. One thing we must keep in our mind is how to begin our hands-on...

3 minutes read.

Importing Numpy in Pycharm

Numpy : Numpy is one of the important library in python. The abbreviation of numpy is “Numerical python” or “Numeric Python”. This library is mainly used to access arrays. Numpy was created...

5 minutes read.

Python vs PHP

Python Python is a high-level, object-oriented, interpreted language that is used to create independent program and algorithms for a variety of applications. It has a large library support base. In 1990,...

3 minutes read.

Python Algorithms

A quote goes, "A goal without a plan is just a wish." To achieve anything in life, we can't simply go for it without making a plan and sticking to...

4 minutes read.

Python Queue

Python Queue There are various day to day activities where we find ourselves engaged with queues. Whether it is waiting in toll tax lane or standing on the billing counter for...

7 minutes read.

N2 in Python

N2 is known as Nearest Neighbor Algorithm, because it contains 2 N's (N-Nearest, N-Neighbor). This is a library in the python build using C++ and Python. Before N2 was made,...

3 minutes read.

_dict_ in Python

An unordered collection of data values known as a dictionary can be used in Python to store data values similar to a map. Dictionaries can also store a key: value...

6 minutes read.

Sort Dictionary in Python

Dictionaries In Python, a dictionary is an unordered collection or set of data types that enable of store data in an unordered key-value/pair. The key is stored alongside with value. Dictionary contains key:...

4 minutes read.

What is the Python Global Interpreter Lock?

Introduction When working with processes, Python employs a form of process lock called the Global Interpreter Lock (GIL). Python typically executes a collection of typed statements using just one thread. It...

4 minutes read.

Polymorphism in Python

What is polymorphism and why is it important? Polymorphism's literal definition is the state of occurring in diverse shapes or forms. When it comes to programming, the idea of polymorphism is crucial....

3 minutes read.

How to Download all Modules in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python Stack

Python Stack: The work Stack is defined as arranging a pile of objects or items on top of another. It is the same method of allocating memory in the stack...

10 minutes read.

Fsolve in Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Python program to add two number

Python program to add two number This program will add the two numbers and display their sum on the screen. Example: Input: Number1 = 20        Number2 = 30   Output: Sum =...

2 minutes read.