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.
- Absolute path: The absolute path contains the total directory list on how to locate the file.
- 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.- Absolute path: The absolute path contains the total directory list on how to locate the file.
- 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.