How to Open a file in python with Path
In this tutorial, we will see rather than the traditional way of opening a file by locating or navigating it from our desktops; we will learn how to open the particular file we want using its path in Python from the IDE we are in.
How to Open a file in Python with path.
Steps to open a file in Python with its path
Step:1 - Find the path of the file in which it is located in
There are mainly two significant ways to locate the file: a relative path and an absolute one.
The relative path will contain the complete end-to-end location from the starting desktop directory to the final place of the file's existence. An absolute path includes the current directory the user is in and then the file name, which is the last location we can say.
Step-2 - It’s time to decide the access mode to open the file
Step-3 - Pass the file path and the access mode we have chosen to the open function to locate and open the file.
Step-4 - Read the content that we would like to from the file opened
Step-5 - Write or edit any changes to the file
Step-6 - Now correctly close the file after completing the operations.
Opening a file in the absolute path in Python
# Opening the file with absolute path file_p = open(r'E:\demos\files\sample.txt', 'r') # read file print(file_p.read()) # Closing the file after reading file_p.close() # path if we are using MacOs # file_p = open(r"/Users/myfiles/sample.txt", "r")
#file opened using absolute path method Welcome to javaTpoint.com This is a sample.txt file end of the file thank you
Opening a File using the Relative Path Method
# Opening the file with relative path try: file_p = open("sample.txt", "r") print(file_p.read()) file_p.close() except FileNotFoundError: print("Please check the path.")
#file opened using relative path method Welcome to javaTpoint.com This is a sample.txt file end of the file thank you
Opening a File in Append Mode
After the file gets opened, we can even append it by using the variable name dot prompt in the braces. This text or prompt we have added will be placed at the end of the file in the text format. See the code below for more understanding
# Open and Appending at the last of the file opened file_p = open("sample2.txt", "a") file_p.write(" Added this line by opening the file in append mode ") # Opening the file again to read file_p = open("sample2.txt", "r") print(file_p.read()) file_p.close()
This is a new line we have added this line by opening a file in the append mode from our IDE itself.