Open a File in Python (2024)

In this tutorial, you’ll learn how to open a file in Python.

The data can be in the form of files such as text, csv, and binary files. To extract data from these files, Python comes with built-in functions to open a file and then read and write the file’s contents.

After reading this tutorial, you can learn: –

  • How to open a file in Python using both relative and absolute path
  • Different file access modes for opening a file
  • How to open a file for reading, writing, and appending.
  • How to open a file using the with statement
  • Importance of closing a file

Table of contents

  • Access Modes for Opening a file
  • Steps For Opening File in Python
    • Example: Opening a File in read mode
    • Opening a File with Relative Path
    • Handling the FileNotFoundError
  • File open() function
  • Opening a File in Read mode
  • Opening a File in Write Mode
  • Opening a File in Append Mode
  • Closing a File
  • Opening file using with statement
  • Creating a new file
  • Opening a File for multiple operations
  • Opening a Binary file
  • Summary

Access Modes for Opening a file

The access mode parameter in the open() function primarily mentions the purpose of opening the file or the type of operation we are planning to do with the file after opening. in Python, the following are the different characters that we use for mentioning the file opening modes.

File ModeMeaning
rOpens a file for reading (default)
wOpen a file for writing. If a file already exists, it deletes all the existing contents and adds new content from the start of the file.
xOpen a file for exclusive creation. If the file already exists, this operation fails.
aOpen a file in the append mode and add new content at the end of the file.
bOpen the file in binary mode.
tOpens a file in a text mode (default).
+Open a file for updating (reading and writing).

Steps For Opening File in Python

To open a file in Python, Please follow these steps:

  1. Find the path of a file

    We can open a file using both relative path and absolute path. The path is the location of the file on the disk.
    An absolute path contains the complete directory list required to locate the file.
    A relative path contains the current directory and then the file name.

  2. Decide the access mode

    The access mode specifies the operation you wanted to perform on the file, such as reading or writing. To open and read a file, use the r access mode. To open a file for writing, use the w mode.

  3. Pass file path and access mode to the open() function

    fp= open(r"File_Name", "Access_Mode"). For example, to open and read: fp = open('sample.txt', 'r')

  4. Read content from a file.

    Next, read a file using the read() method. For example, content = fp.read(). You can also use readline(), and readlines()

  5. Write content into the file

    If you have opened a file in a write mode, you can write or append text to the file using the write() method. For example, fp.write('content'). You can also use the writeine() method.

  6. Close file after completing operation

    We need to make sure that the file will be closed properly after completing the file operation. Use fp.close() to close a file.

Example: Opening a File in read mode

The following code shows how to open a text file for reading in Python. In this example, we are opening a file using the absolute Path.

An absolute path contains the entire path to the file or directory that we need to access. It includes the complete directory list required to locate the file.

For example, /home/reports/samples.txt is an absolute path to discover the samples.txt. All of the information needed to find the file is contained in the path string.

See the attached file used in the example and an image to show the file’s content for reference.

Open a File in Python (1)
# Opening the file with absolute pathfp = open(r'E:\demos\files\sample.txt', 'r')# read fileprint(fp.read())# Closing the file after readingfp.close()# path if you using MacOs# fp = open(r"/Users/myfiles/sample.txt", "r")Code language: Python (python)

Output

Welcome to PYnative.comThis is a sample.txt

Opening a File with Relative Path

A relative path is a path that starts with the working directory or the current directory and then will start looking for the file from that directory to the file name.

For example, reports/sample.txt is a relative path. In the relative path, it will look for a file into the directory where this script is running.

# Opening the file with relative pathtry: fp = open("sample.txt", "r") print(fp.read()) fp.close()except FileNotFoundError: print("Please check the path.")Code language: Python (python)

Handling the FileNotFoundError

In case we are trying to open a file that is not present in the mentioned path then we will get a FileNotFoundError.

fp = open(r'E:\demos\files\reports.txt', 'r')print(f.read())Code language: Python (python)

Output

FileNotFoundError: [Errno 2] No such file or directory: 'E:\demos\files\reports.txt'

We can handle the file not found error inside the try-except block. Let us see an example for the same. Use except block to specify the action to be taken when the specified file is not present.

try: fp = open(r'E:\PYnative\reports\samples.txt', 'r') print(fp.read()) fp.close()except IOError: print("File not found. Please check the path.")finally: print("Exit")Code language: Python (python)

Output

File not found. Please check the path.Exit

File open() function

Python provides a set of inbuilt functions available in the interpreter, and it is always available. We don’t have to import any module for that. We can open a file using the built-in function open().

Syntax of the file open() function

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)Code language: Python (python)

It return the file object which we can sue to read or write to a file.

Parameters:

Let us see the parameters we can pass to the open() function to enhance the file operation.

ParameterDescription
fileThis parameter value gives the pathname (absolute or relative to the current working directory) of the file to be opened.
modeThis is the optional string that specifies the mode in which a file will be opened. The default value is 'r' for reading a text file. We can discuss the other modes in the later section.
bufferingThis is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size in bytes of a fixed-size chunk buffer.
encodingThis is the name of the encoding used to decode or encode the file.The default one is platform dependant.
errorsThese are optional string denotes how the standard encoding and decoding errors have to be handled.
newlineThis is the parameter that indicates how the newline mode works (it only applies to text mode). It can beNone,'','\n','\r', and'\r\n'.
closefdThis parameter indicates whether to close a file descriptor or not. The default value is True. If closefdisFalseand a file descriptor rather than a filename was given, the underlying file descriptor will be kept open when the file is closed.

Opening a File in Read mode

We can open a file for reading the contents of a file using the open() function and passing the r mode. This will open the file only for reading the contents, and we can’t use it for anything else like writing new content.

The file can basically in two categories namely flat files and non flat files.

  • Flat files are the ones that are not properly indexed, like .csv (comma separated values), where each record has different comma-separated values. But they are not ordered with an index. They generally have one record per line and in general, have a fixed set of values in each record.
  • Nonflat files are the ones with proper index values. Each record will have one index value, and we can easily find one using the index value.

Consider that we are having a file called ‘sample.txt’ and we are opening the file for reading its contents.

try: fp = open("sample.txt", "r") # Reading the contents of the file and closing print(fp.read()) fp.close()except IOError: print("Please check the path.")Code language: Python (python)

Output

Welcome to PYnative.comThis is a sample.txt

Read More: Complete Guide on Reading Files in Python

Opening a File in Write Mode

We can open a file for writing new contents into a file using the open() function with w as the access mode. The cursor or the file pointer will be placed at the beginning of the file.

Note: If the file is already present it will truncate the file, which means all the content previously in the file will be deleted, and the new content will be added to the file.

fp = open("sample2.txt", "w")# Writing contentfp.write("New line")# Opening the file again for reading the contentfp = open("sample2.txt", "r")# Reading the contents of the file and closingprint(fp.read())fp.close()Code language: Python (python)

Output

New line

Read More: Complete Guide on Write to File in Python

Opening a File in Append Mode

We can append some content at the end of the file using the open() function by passing the character a as the access mode. The cursor will be placed at the end of the file, and the new content will get added at the end.

The difference between this and the write mode is that the file’s content will not be truncated or deleted in this mode.

Consider that the file “sample2.txt” is already created and there is some content in the file. Now we are opening the file in the append mode and trying to add some content at the end of the file.

# Open and Append at lastfp = open("sample2.txt", "a")fp.write(" Added this line by opening the file in append mode ")# Opening the file again to readfp = open("sample2.txt", "r")print(fp.read())fp.close()Code language: Python (python)

Output

New lineAdded this line by opening a file in the append mode 
Open a File in Python (2)

Closing a File

We need to make sure that the file will be closed properly after completing the file operation. It is a bad practice to leave your files open.

In Python, It is very important to close a file once the job is done mainly for the following reasons: –

  • It releases the resources that have been tied up with the file. By this space in the RAM can be better utilized and ensures a better performance.
  • It ensures better garbage collection.
  • There is a limit to the number of open files in an application. It is always better to close the file to ensure that the limit is not crossed.
  • If you open the file in write or read-write mode, you don’t know when data is flushed.

A file can be closed just by calling the close() function as follows.

# Opening the file to read the contentsf = open("sample2.txt", "r")print(f.read())# Closing the file once our job is donef.close()Code language: Python (python)

Opening file using with statement

We can open a file using the with statement along with the open function. The general syntax is as follows.

with open(__file__, accessmode) as f:Code language: Python (python)

The following are the main advantages of opening a file using the with statement

  • The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks.
  • This also ensures that a file is automatically closed after leaving the block.
  • As the file is closed automatically it ensures that all the resources that are tied up with the file are released.

Let us see how we can the with statement for opening a file with an example. Consider there are two files ‘sample.txt’ and ‘sample2.txt’ and we want to copy the contents of the first file to the second.

# Opening filewith open('sample.txt', 'r', encoding='utf-8') as infile, open('sample2.txt', 'w') as outfile: # read sample.txt an and write its content into sample2.txt for line in infile: outfile.write(line)# Opening the file to read the contentsf = open("Sample2.txt", "r")print(f.read())f.close()Code language: Python (python)

Output

Welcome to PYnative.comFile created to demonstrate file handling in Python

Here we can see that the contents of the sample2.txt has been replaced by the contents of sample.txt.

Creating a new file

We can create a new file using the open() function by setting the x mode. This method will ensure that the file doesn’t already exist and then create a new file. It will raise the FileExistsError if the file already exists.

Example: Creating a new file.

try: # Creating a new file with open("sample3.txt", "x") as fp: fp.write("Hello World! I am a new file") # reading the contents of the new file fp = open("sample3.txt", "r") print(fp.read())except FileExistsError: print("The file already exists")Code language: Python (python)

Output

Hello World! I am a new file

Opening a File for multiple operations

In Python, we can open a file for performing multiple operations simultaneously by using the '+' operator. When we pass r+ mode then it will enable both reading and writing options in the file. Let us see this with an example.

with open("Sample3.txt", "r+") as fp: # reading the contents before writing print(fp.read()) # Writing new content to this file fp.write("\nAdding this new content")Code language: Python (python)

Opening a Binary file

Binary files are basically the ones with data in the Byte format (0’s and 1’s). This generally doesn’t contain the EOL(End of Line) so it is important to check that condition before reading the contents of the file.

We can open and read the contents of the binary file as below.

with open("sample.bin", "rb") as f: byte_content = f.read(1) while byte_content: # Printing the contents of the file print(byte_content)Code language: Python (python)

Summary

In this tutorial, we have covered how to open a file using the different access modes. Also, we learned the importance of opening a file using the ‘with’ statement.

Open a File in Python (2024)
Top Articles
Greenest Cryptocurrencies to Invest In – Beginner’s Guide for 2024
How to set or change shared link permissions
Safety Jackpot Login
Blorg Body Pillow
Genesis Parsippany
Trevor Goodwin Obituary St Cloud
Ffxiv Shelfeye Reaver
Combat level
Tyson Employee Paperless
Repentance (2 Corinthians 7:10) – West Palm Beach church of Christ
Driving Directions To Fedex
How to change your Android phone's default Google account
Comcast Xfinity Outage in Kipton, Ohio
craigslist: south coast jobs, apartments, for sale, services, community, and events
Www Craigslist Louisville
Paula Deen Italian Cream Cake
The Haunted Drury Hotels of San Antonio’s Riverwalk
Lesson 3 Homework Practice Measures Of Variation Answer Key
Youtube Combe
Moe Gangat Age
Simon Montefiore artikelen kopen? Alle artikelen online
Hartland Liquidation Oconomowoc
Viha Email Login
Nba Rotogrinders Starting Lineups
Saatva Memory Foam Hybrid mattress review 2024
13301 South Orange Blossom Trail
Cal State Fullerton Titan Online
8002905511
Craigslist Gigs Norfolk
Phone number detective
Palmadise Rv Lot
2012 Street Glide Blue Book Value
Seymour Johnson AFB | MilitaryINSTALLATIONS
Orangetheory Northville Michigan
Naya Padkar Newspaper Today
The Blackening Showtimes Near Regal Edwards Santa Maria & Rpx
Los Garroberros Menu
Mckinley rugzak - Mode accessoires kopen? Ruime keuze
All Obituaries | Sneath Strilchuk Funeral Services | Funeral Home Roblin Dauphin Ste Rose McCreary MB
Chathuram Movie Download
Valls family wants to build a hotel near Versailles Restaurant
Citizens Bank Park - Clio
About Us
Top 1,000 Girl Names for Your Baby Girl in 2024 | Pampers
8 4 Study Guide And Intervention Trigonometry
Theater X Orange Heights Florida
Skyward Login Wylie Isd
Tommy Gold Lpsg
Marion City Wide Garage Sale 2023
Bomgas Cams
Tamilyogi Cc
Ff14 Palebloom Kudzu Cloth
Latest Posts
Article information

Author: Melvina Ondricka

Last Updated:

Views: 5993

Rating: 4.8 / 5 (48 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Melvina Ondricka

Birthday: 2000-12-23

Address: Suite 382 139 Shaniqua Locks, Paulaborough, UT 90498

Phone: +636383657021

Job: Dynamic Government Specialist

Hobby: Kite flying, Watching movies, Knitting, Model building, Reading, Wood carving, Paintball

Introduction: My name is Melvina Ondricka, I am a helpful, fancy, friendly, innocent, outstanding, courageous, thoughtful person who loves writing and wants to share my knowledge and understanding with you.