Open In App
Related Articles

Open a File in Python

Improve Article
Improve
Save Article
Save
Like Article
Like

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 in Python

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. The file handle is like a cursor, which defines where the data has to be read or written in the file. There are 6 access modes in Python.

Mode

Description

‘r’Open text file for reading. Raises an I/O error if the file does not exist.
‘r+’Open the file for reading and writing. Raises an I/O error if the file does not exist.
‘w’Open the file for writing. Truncates the file if it already exists. Creates a new file if it does not exist.
‘w+’Open the file for reading and writing. Truncates the file if it already exists. Creates a new file if it does not exist.
‘a’Open the file for writing. The data being written will be inserted at the end of the file. Creates a new file if it does not exist.
‘a+’Open the file for reading and writing. The data being written will be inserted at the end of the file. Creates a new file if it does not exist.
‘rb’Open the file for reading in binary format. Raises an I/O error if the file does not exist.
‘rb+’Open the file for reading and writing in binary format. Raises an I/O error if the file does not exist.
‘wb’Open the file for writing in binary format. Truncates the file if it already exists. Creates a new file if it does not exist.
‘wb+’Open the file for reading and writing in binary format. Truncates the file if it already exists. Creates a new file if it does not exist.
‘ab’Open the file for appending in binary format. Inserts data at the end of the file. Creates a new file if it does not exist.
‘ab+’Open the file for reading and appending in binary format. Inserts data at the end of the file. Creates a new file if it does not exist.

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

Opening a file in read mode in Python

In this example, we are reading data from a Txt file. We have used read() to read the data.

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("myfile.txt")
 
# 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.

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" , "a" )
 
# Writing to file
file1.write("\nWriting to file:)" )
 
# Closing file
file1.close()

Output:

Open a File in Python

 

Opening a file with write mode in Python

In this example, we are using ‘w+’ which deleted the content from the file, writes some data, and moves the file pointer to the beginning.

Python3




# Open a file for writing and reading
file = open('test.txt', 'w+')
 
# Write some data to the file
file.write('Hello, world!')
 
# Move the file pointer back to the beginning of the file
file.seek(0)
 
# Read the data from the file
data = file.read()
 
# Print the data to the console
print(data)
 
# Close the file when you're done
file.close()

Output :

Open a File in Python

Hello World 

Python Hello World

Terminal Output

Reading Data from File Using Line By Line Using readline()

The readline() method in Python is used to read a single line from a file that has been opened for reading. When readline() is used in the code, it reads the next line of the file and returns it as a string.

In this example, we are reading data line by line from a file named test.txt and printing it into the terminal.

Python3




# Open a file for reading
file = open('test.txt', 'r')
 
# Read the first line of the file
line = file.readline()
 
# Loop through the rest of the file and print each line
while line:
    print(line)
    line = file.readline()
 
# Close the file when you're done
file.close()

Readline file

Test file

Output:

Readline Python Output

Terminal output


Last Updated : 30 May, 2023
Like Article
Save Article
Similar Reads
Related Tutorials