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:
- r -> read-only
- w -> write only
- x -> exclusive file creation
- a -> append-only
- t -> text mode
- b -> binary mode
As the letters indicate,
- 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.
- 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.
- 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.
- 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.
- t opens the file in text format
- 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.
- r+: read and write
- 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?
- 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.
- 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.
- 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.
- rb: To open a binary file in reading mode.
- wb: To open a binary file in write mode.
- 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:

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

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:

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

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:

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:

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:
- If we want to write into it, we need to encode the data.
- 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:

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