×

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 range() function

Python range() function The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. Syntax range(stop)        or range(start, stop[, step]) Parameter start: It is...

1 minute read.

Tensorflow Angular in Python

TensorFlow is an open-source, Python-compatible toolkit for numerical computation that accelerates and simplifies the creation of neural networks and machine learning algorithms. They make the interesting notion that models can be...

6 minutes read.

Latest Project Ideas using Python 2024

Python is one of the well-known languages for programming in the contemporary domain of computer science. The demand to adopt Python for IT purposes is steadily increasing because of its...

7 minutes read.

Python program to find the GCD or HCF

Python program to find the GCD or HCF The largest positive integer that perfectly divides the two numbers is the HCF (Highest Common Factor) or GCD (Greatest Common Deviser). For example,...

5 minutes read.

Python String lower() method

Python String lower() method The string.lower() method in Python returns a string where all characters are lower case. Syntax string.lower() Parameter NA Return This method returns a string where all characters are lower case. Example 1 # Python...

1 minute read.

How to set font for Text in Python

As a tuple with the font family as the first component, a size in point as the second, and possibly a string with one or more of the style modifiers...

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

How to read data from com port in python

Comport, the I/O interface is known as a COM port that allows the connection for a serial device to a computer. COM ports are sometimes referred to as serial ports....

3 minutes read.

How to run Python program in CMD

How to run python program in cmd Command Prompt provides us all together with a different approach for dealing with our programs. The programs can be executed by accessing the directories. In...

3 minutes read.

Python callable() Function

Python callable() Function The callable() function returns a boolean value ‘True’ if the specified object is callable, else it returns False. Syntax callable(object) Parameter Object:  The object parameter represents the value to test if it is callable...

1 minute read.

What is Python online compiler?

The compiler is a program that is used to scan an entire high-level program (source code) and it translates the scanned program into machine code. Compilers convert .py source code into...

5 minutes read.

Python Program to Convert Decimal into Binary, Octal, and Hexadecimal

Python Program to Convert Decimal into Binary, Octal, and Hexadecimal We know that the most widely used number system is a decimal system, but the computer only understands binary values. The...

2 minutes read.

Python vs Java

There are a lot of programming languages out there, and every day, a new programming language is developing in some parts of the world. Each programming language is a mixture...

5 minutes read.

wxPython Panel class

wxPython Panel class The Widgets which is shown in the frame of GUI window such as text box, buttons, static text etc. are put inside the panel class of the wxpython...

2 minutes read.

Python Read Excel file

Python Read Excel file Excel is the spreadsheet application for Window, which is developed by Microsoft. The Excel stores data in the tabular form. It provides easy access to analyze and maintain the...

3 minutes read.

Best Way to Learn Python for Free

Python is a booming language these days. It has many applications for making code easier; it is also an open-source language. Learning Python is a step towards coding. Python gets...

5 minutes read.

End Parameter in python

print(): The python print() function prints the program’s output to the output screen. The output can be an integer value, string value or other value. Syntax: print(“hi”) Output: hi will be displayed on the output...

3 minutes read.

Speech Recognition Module in Python

Speech Module in Python: Converting text to speech, known as Speech Synthesis, this process is the computer-generated recreation of human speech. This module converts the human language text into human-like...

8 minutes read.

Python Support

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.

Adding item to a python dictionary

The dictionary is one of python’s built-in data structures where it stores key-value pairs. A dictionary is a collection of ordered values that can be changeable. We can add, modify,...

3 minutes read.