Skip to content
Related Articles

Related Articles

Open a File in Python

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 13 Jun, 2022

Python provides inbuilt functions for creating, writing, and reading files. There are two types of files that can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s).

  • Text files: In this type of file, each line of text is terminated with a special character called EOL (End of Line), which is the new line character (‘\n’) in Python by default. In the case of CSV(Comma Separated Files, the EOF is a comma by default.
  • Binary files: In this type of file, there is no terminator for a line, and the data is stored after converting it into machine-understandable binary language, i.e., 0 and 1 format.

Refer to the below articles to get an idea about the basics of file handling.

Opening a file

Opening a file refers to getting the file ready either for reading or for writing. This can be done using the open() function. This function returns a file object and takes two arguments, one that accepts the file name and another that accepts the mode(Access Mode). Now, the question arises what is the access mode? Access modes govern the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. These modes also define the location of the File Handle in the file. File handle is like a cursor, which defines from where the data has to be read or written in the file. There are 6 access modes in python.

  • Read Only (‘r’): Open text file for reading. The handle is positioned at the beginning of the file. If the file does not exist, raises an I/O error. This is also the default mode in which the file is opened.
  • Read and Write (‘r+’): Open the file for reading and writing. The handle is positioned at the beginning of the file. Raises I/O error if the file does not exist.
  • Write Only (‘w’): Open the file for writing. For the existing files, the data is truncated and over-written. The handle is positioned at the beginning of the file. Creates the file if the file does not exist.
  • Write and Read (‘w+’): Open the file for reading and writing. For existing files, data is truncated and over-written. The handle is positioned at the beginning of the file.
  • Append Only (‘a’): Open the file for writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
  • Append and Read (‘a+’): Open the file for reading and writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
  • Read Only in Binary format(‘rb’):  It lets the user open the file for reading in binary format.
  • Read and Write in Binary Format(‘rb+’): It lets the user open the file for reading and writing in binary format.
  • Write Only in Binary Format(‘wb’): It lets the user open the file for writing in binary format. When a file gets opened in this mode, there are two things that can happen mostly. A new file gets created if the file does not exist. The content within the file will get overwritten if the file exists and has some data stored in it. 
  • Write and Read in Binary Format(‘wb+’):  It lets the user open the file for reading as well as writing in binary format. When a file gets opened in this mode, there are two things that can mostly happen. A new file gets created for writing and reading if the file does not exist. The content within the file will get overwritten if the file exists and has some data stored in it. 
  • Append only in Binary Format(‘ab’): It lets the user open the file for appending in binary format. A new file gets created if there is no file. The data will be inserted at the end if the file exists and has some data stored in it. 
  • Append and Read in Binary Format(‘ab+’): It lets the user open the file for appending and reading in binary format. A new file will be created for reading and appending if the file does not exist. We can read and append if the file exists and has some data stored in it.  

Syntax:

File_object = open(r"File_Name", "Access_Mode")

Note: The file should exist in the same directory as the Python script, otherwise full address of the file should be written. If the file is not exist, then an error is generated, that the file does not exist.

open-file-python

Example #1: Opening a file in read mode in Python. 

Python3




# Python program to demonstrate
# opening a file
 
 
# Open function to open the file "myfile.txt"
# (same directory) in read mode and store
# it's reference in the variable file1
 
file1 = open(& quot
              myfile.txt & quot
              )
 
# Reading from file
print(file1.read())
 
file1.close()

Output:

Welcome to GeeksForGeeks!!

Note: In the above example, we haven’t provided the access mode. By default, the open() function will open the file in read mode, if no parameter is provided.

Example #2: Adding data to the existing file in Python 

If you want to add more data to an already created file, then the access mode should be ‘a’ which is append mode, if we select ‘w’ mode then the existing text will be overwritten by the new data.

Python3




# Python program to demonstrate
# opening a file
 
 
# Open function to open the file "myfile.txt"
# (same directory) in append mode and store
# it's reference in the variable file1
file1 = open(" myfile.txt" , & quot; a" )
 
# Writing to file
file1.write(" \nWriting to file:)" )
 
# Closing file
file1.close()

Output:

python-open-file 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!