×

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 Ways to find nth occurrence of substring in a string

Introduction In Python, a string is a collection of characters that can be employed to conduct additional operations. In Python, a substring is a group of characters that are a part...

4 minutes read.

Python Recursion

Recursion is one of the most interesting yet important concepts of any programming language. If you want to be a good programmer or data scientist, then you should better have...

4 minutes read.

Python locals() function

Python locals() function The locals() function in Python updates and returns a dictionary representing the current local symbol table. Syntax locals() Parameter NA Return This function returns the local symbol table as a dictionary or returns free...

1 minute read.

How to get Time in seconds in Python

Python's time module source shows that are based on time. The time() method is used by developers and returns the current time as a UNIX timestamp. A UNIX timestamp is...

4 minutes read.

How to Concat two Dataframes in Python

Using Pandas dataframe, we can concat two dataframes or series in Python. So let's take a brief introduction to what is Pandas in Python. Pandas is a library typically used for...

7 minutes read.

Handling missing keys in Python dictionaries

In this lesson, you will discover how to create a Python application that will manage missing keys in a dictionary. Python dictionaries store data as key-value pairs, where each value...

3 minutes read.

Python Write Excel File

Python Write Excel File The Python xlwt module is used to write an excel file and perform multiple operations on it. It can be used to write text, numbers, and formulas for multiple...

3 minutes read.

Python Arithmetic Operators

An arithmetic operator is a mathematical operator that is used to operate on two operands. Based on the operator used, action is performed on the operands, and output is delivered. Following...

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

os.rename() method in Python

In Python, the os module provides the capacity to interact with the operating system. The operating system comes under the Python module. In this module, Python provides a specific feature...

3 minutes read.

Python OOPs: Class, Object, Inheritance and Constructor

Basic Object-Oriented Programming (OOP) Concepts in Python Python is similar to most general-purpose programming languages with an Object-Oriented environment system since its existence. Being an Object-Oriented Programming language, Python provides ease...

9 minutes read.

Python pynmea2

Define Pynmea2 Python Programming Language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in...

4 minutes read.

Reading a File Line by Line in Python

Introduction In this tutorial, we will learn about reading files in python line by line. Before reading the files, let us know a little information about the files first. Files A file is...

6 minutes read.

How to Concatenate Two Strings in Python

How to Concatenate Two Strings in Python Like the other data types, operations on strings are quite useful when we deal with some real-life applications. Here we will talk about a simple...

4 minutes read.

Google Python Class

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Difference between Python and CPP

Difference between Python and C++ We all know that both C++ and Python are two of the most popular programming languages. Both C++ and Python shares some basic similarities such as...

6 minutes read.

Difference between Mutable and Immutable Objects

Difference between Mutable and Immutable Objects As we all know that Python is an object-oriented programming language. Object-oriented programming approach is based on the objects and the classes’ stores the data...

4 minutes read.

Python format() function

Python format() function The format() function in Python formats a specified value into the given format. A ‘TypeErrorexception’ is raised if the method search reaches the object and the format_spec is non-empty, or if either the format_spec or the...

1 minute read.

Socket Programming in Python

Socket Programming in Python In this tutorial, we will discuss network programming using Python programming language. We will explore all basic concept of network with Python script. Network Services in Python Python has...

9 minutes read.

String indices must be integers in Python

Lists, tuples, and strings are examples of iterable objects in Python whose items or characters can be retrieved by their index numbers. For instance, you might take the following action to...

3 minutes read.