×

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 Boolean

In this article, you will learn the boolean variables in python, bool() function in python, and bool operators with examples, Boolean Objects in Python. There are the only two possible values...

6 minutes read.

Sort a dataframe based on a column in Python

Sorting the dataframe based on a column requires pandas which is An open-source library called Python Pandas is described as offering high-performance data processing in Python. For both professionals and...

4 minutes read.

Python EOL (End Of Line)

Introduction An EOL (End Of Line) is defined as a syntax error that indicates that the Python interpreter reached at the end of the line when it tried to scan a...

3 minutes read.

Dictionary to JSON Python

In python JSON (JavascriptObject Notation). In the programming language, the text file is made using the script file.We can use many built-in packages which arenamedJSON.Before using the packages, we have...

3 minutes read.

Paramiko Python Example

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

6 minutes read.

Add Dictionary to Dictionary in Python

Dictionary in python: Python's execution of a data model, known more commonly as an implicit array, is a dictionary. A dictionary is made up of a group of key-value pairs. Each...

4 minutes read.

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

Matrix List Comprehension in Python

Introduction One of Python's most beautiful features is list comprehension. Iterating over an iterable object to create lists is a clever and succinct method. Nested List or matrix list Comprehensions, which...

6 minutes read.

Convert Float to Int in Python using Pandas

Introduction To play with huge amounts of data, in python we require a tool. The tool which is available in Python is pandas. A panda is an open-source library. It is...

4 minutes read.

Decision Tree in Python

Decision Tree is one of the most essential algorithms in the area of machine learning for classification and regression. But let us first talk about the lifespan of every machine learning...

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

Convert XML to JSON in Python

XML conversion is very useful if we work on an API that returns data in JSON format and the source of data is in XML format. JSON A JSON file reserves the...

4 minutes read.

Best Way to Learn Python for Free

Python is a booming language these days. It has many applications for making code easier; it is also an open-source language. Learning Python is a step towards coding. Python gets...

5 minutes read.

ComboBox in Python

Python includes several graphical user interface (GUI) libraries, including PyQT, Tkinter, Kivy, WxPython, and PySide. Tkinter is the most commonly used GUI module in Python because it is simple and...

2 minutes read.

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

4 minutes read.

Python String expandtabs() method

Python String expandtabs() method The string.expandtabs() method in Python returns a copy of the string where all tab characters are expanded using spaces. Syntax String.expandtabs([tabsize]) Parameter tabsize: This parameter specifies the number of characters to...

1 minute read.

Permutations in Python

Recursion Basic idea: for numbers of length N. N-1 items are chosen at random between 0 and then generate permutations using the remaining N-1 elements in a recursive fashion. Once you've done...

4 minutes read.

SKLearn Clustering

These are ml methods thatare responsible for detecting patterns and the similarities within the data.The clustering methods are unsupervised.Here the data is clustered to form groups with the help of...

3 minutes read.

Create First GUI Application using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

6 minutes read.

CSV Write in Python

What is meant by CSV? CSV stands for Comma Separated Values. The name itself defines its purpose. CSV arranges the data in the form of tables and stores the organized data in...

3 minutes read.