×

How to Open a File in Python with a Path?

File in Python

File handling is an important operation; it allows the programmer to access the data in the files, such as text, binary values and excel sheets. The CSV files contain a massive amount of data; it mainly helps the data scientists deal with it. The file handling can be easily implemented in the python programming language. Python can easily identify the difference between binary values and text; this is a critical feature. Python can understand if a line in the file is terminated based on some special characters known as the END OF LINE CHARACTERS (EOL). These characters signal to the interpreter that the current line is terminated and a new line has begun.

Types of Files

The files are classified based on the data present in them. Generally, the files are categorized into two types one contains the data in the form of text and the other consists of the binary, which can be understandable by only the machines; it consists of the 0s and 1s

  • Text files: The text files consist of the characters, and each line in the text file is terminated with the help of special characters known as the END OF LINE (EOL); it indicates to the interpreter that the current line has come to an end and we need to start the new line. The EOL helps in segregating the specific lines. The text files have an extension of “.txt."
  • Binary files: The binary files consists of the data in the form of 0s and 1s.These files do not contain terminators such as the EOL in the binary files. The python interpreter first receives the data from the binary file, and the python interpreter will obtain the data in binary language.

Opening a File in Python

To perform any operations, such as adding any data or removing the data present in the text files, first, we need to open the file to perform any operations on it. To perform this operation, python provides the in-built function open( ), which helps to open the file and create a file object. For using the open( ) function in python, we don't need to import any packages or libraries.

Syntax:

Object_File= open(r “Name of the File”, “ Accessing modes of file” )

Parameters:

  • Name of the file: This parameter includes the file's name, or it allows the file's path. Generally, if we want to include the file's name without the file's path, we must ensure that the text file and the python script are inside the same directory. If we want the path of the file, then we need to include the 'r' character before the file path. The file's path is generally created into two types: absolute and relative paths.
    1. Absolute path: The absolute path contains the total directory list on how to locate the file.
    2. Relative path: The relative path contains the data about the current directory and the file's name.
  • Accessing modes of file: The accessing modes of python define how we can access the file of our type and what type of file we want to open. The ‘r’, ‘w’, and ‘a’ are the characters used to perform the read, write and append operations, allowing the type of file we need to access. To access the text file, we need to include the ‘t’ character; for the binary file, we need to include the letter ‘b’. If we do not include any character for the file type, the file is default set as the text file. If we want to write any data in the binary file, we need to use the “wb” letter.

Different Modes of Accessing

Access Mode                                   Operations
‘x’This letter is used to create an empty file,
‘r’This letter is used to open the file in read-only mode to perform this operation; the file must be pre-initialized.
‘w’This letter is used to open the file in write-only mode; if the file is pre-initialized, it will be exchanged by the data we provide. If the file is not pre-initialized, then we need to create the file.
‘a’This letter is used to open the file in write-only mode. If the file must be pre-initialized, it will be appended by the data provided by the user; if it is not pre-initialized, then we need to create the file.
‘r+’This letter is used to open the file in both reading and writing mode to perform this operation; the file should be pre-initialized.
‘w+’This letter opens the file in both reading and writing mode. If the file is pre-initialized, it will be exchanged by the data we provided. If the file is not pre-initialized, we need to create the file to perform this operation.
‘a+’This letter opens the file in both reading and writing mode. If the file is pre-initialized, then the data is appended at the end, and if not, the file will be created to perform this operation.

To open the file in python, we need to follow certain steps:

  • Selecting the path of the file:
    The path helps in locating the file on the hard disk. We can open the file in the absolute path or the relative path.
    1. Absolute path: The absolute path contains the total directory list on how to locate the file.
    2. Relative path: The relative path contains the data about the current directory and the file's name.
  • Accessing modes of the file:
    The file can be accessed in many ways, as mentioned above in the accessing modes. To open the file in reading mode, we need to use the ‘r’ character; to open the file in append mode; we need to use the ‘a’ character.
  • Passing the path of the file and accessing mode to the open( ) function:
    To open the file,we need to pass the parameters such as the name of the file or the path and the accessing mode of the file. For example to open a file and write in the file: f = open (‘data.txt’, ‘w’).
  • Reading the content from the file:
    Python provides the read( ) function to read the content from the file. readline( ) and readlines( ) are also the functions provided to read the content from the file.
    Example:data = f.read( )
  • Writing the content into the file:
    Python provides the various functions such aswrite( ) and writeline( )methods to perform this operation; we can append or write the data into the file.

Example: f.write(‘Data’)

  • Closing the file:
    After completing all the operations on the file, we need to close the file properly. We can close the file by using the following command f.close( )

Opening the File Using the Absolute Path

First, we must open the file by passing the parameters into the open() function. The absolute file contains the complete directory for accessing the file, and this includes the entire path of how to access the file from the disk.

Example:/home/results/data.txt; this is an example of the absolute path; it contains the students' results in the text format in the data file.

Code:

#open the file by using the absolute path
f = open(r ‘E:\marks\results\data.txt’,  ‘r’)
# reading the file
Print(f.read( ))
#Close the file after performing the operation
f.close( )

Output:

The marks of the students are
Nicholas: 96
Nikitha: 93
Solomon: 85

Opening the File Using a Relative Path

First, we must open the file by passing the parameters into the open() function. The relative path provides the information about the current directory, and then it will access the file from that directory to the file name.

Example:results/data.txt; this is an example of the absolute path; it contains the student's results in the text format in the data file. This operation can be performed by using the try and exception block.

Code:

#open the file using the relative path
Try:
     f = open(“data.txt”, “r”)
#reading the file
     print( f.read( ) )
#closing the file
     f.close( )
except FileNotFound:
     print(“Error occurred check the path”)

Output:

FileNotFound: [Error 2]  no file or directory : ‘E:\marks\results\data.txt’

We can remove this error with the help of the try and exception block. The try block will be executed if the file is present in the provided path, the except block will be executed if the file is not present, and finally, statement will also be executed.

Code:

#open the file using the relative path
try:
     f = open(“data.txt”, “r”)
#reading the file
     print( f.read( ) )
#closing the file
     f.close( )
except FileNotFound:
     print("Error occurred! check the path")
finally:
     print(“Exit”)

Output:

Error occurred! check the path
Exit

Here we can observe that no error has occurred, and we can also see the output if the file is not found in the disk with the help of the try and exception block.


Related Topics

Python List copy() method

Python List copy () method The list.copy () method returns a shallow copy of the list. Syntax list.copy() Parameter NA Return This function returns the copy for the given list. Example 1 # Python program explaining # the list.copy() method # passing the...

1 minute read.

Read Text files in Python

In Python, there are many ways to read text files. Before going into the detailed structure of reading a text file, let us understand how reading text files takes place...

4 minutes read.

Python zip() Function

Python zip() Function The zip() function makes an iterator that aggregates elements from each of the iterables and returns an iterator of tuples. Syntax zip(*iterables) Parameter iterables: Iterator objects that will be joined together Return This function...

1 minute read.

Python float()

Python float() class The float() class in Python returns a floating point number constructed from a number or string x. Syntax class float([x]) Parameter x: This parameter represents a number or a string that can be converted...

1 minute read.

Python reversed() Function

Python reversed() Function The reversed() in Python returns a reverse iterator. Syntax reversed(seq) Parameter seq: This parameter represents any iterable object. Return This function returns a reversed iterator object. Example 1 # Python Program describing # the reversed() function ...

1 minute read.

Calculator Program in Python

Simple Calculator Program in Python This example helps to learn how to create a simple calculator program to perform operations like addition, subtraction, multiplication, and division. Source Code The following is the source...

2 minutes read.

Python Sending Email

Python Sending Email Simple Mail Transfer Protocol (SMTP) is used to handle sending e-mail and routing e-mail between mail servers. When we send an email either form a web-application or from a local software...

3 minutes read.

Add Element to Tuple in Python

Python: Popular high-level, all-purpose programming language Python. The new version of the Python programming language, Python 3, is used for all software applications, including web development. Python is the best programming...

4 minutes read.

Python Knapsack problem

Python Knapsack problem Before we dig down about Knapsack problems in Python, first let's have a look at what is actually a knapsack problem. What is a knapsack problem? A problem from the...

5 minutes read.

Python Dictionary values() method

Python Dictionary values() method The dictionary.values() method in Python returns a view object that displays a list of all the values in the specified dictionary. Syntax dictionary.values() Parameter NA Return This method returns a view object. The...

1 minute read.

Python Parallel Processing

By performing more jobs concurrently, your software may complete more tasks in a shorter amount of time. These aid in solving major issues. The following subjects will be covered in...

2 minutes read.

Python program to find the area of the triangle

Python program to find the area of the triangle This article will discuss how to find the area of a triangle in Python with all three given sides. The area of...

2 minutes read.

How to set up a proxy using selenium in python

What is Proxy? A proxy acts as a middleman between user requests and server responses. The main purposes of proxies are to protect user privacy and encapsulate data between various interactive...

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

Python K-Means Clustering

K-Means Clustering is a basic yet incredible calculation in information scienceThere are a plenty of true utilizations of K-Means clustering (a couple of which we will cover here)This far reaching...

25 minutes read.

How to convert Float to Int in Python?

A float value can be converted to an int via type conversion, an explicit method of transforming an operand to a certain type. But it must be noted that such...

3 minutes read.

How to assign values to variables in Python and other languages?

Python makes it simple to construct variables. The value to be stored in the variable should then be written after a suitable name for the variable and the equality sign....

3 minutes read.

Linear Regression using Sklearn with Example

This article will examine Python's global, local and non-local variables and show you how to use them to write code without problems. Let's quickly review what a variable in Python is...

8 minutes read.

What is the Python Global Interpreter Lock?

Introduction When working with processes, Python employs a form of process lock called the Global Interpreter Lock (GIL). Python typically executes a collection of typed statements using just one thread. It...

4 minutes read.

Python dir() function

Python dir() function The dir() function in Python returns all properties and methods of the specified object, without the values. Syntax dir([object]) Parameter object: This parameter represents the object one wants to see the valid attributes. Return This function...

2 minutes read.