×

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

Code

# 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")

Output

#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

Code

# 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.")

Output

#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

Code

# 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()

Output

This is a new line
we have added this line by opening a file in the append mode from our IDE itself.

Related Topics

Python Program to find the length of a string

Python program to find the length of a string A string in Python is a set of Unicode characters. It can't be changed once it's been declared. The number of characters...

2 minutes read.

Working with files in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has an...

5 minutes read.

Important Difference between Python 2.x and Python 3.x with Example

The comparison between Python 2 and Python 3 is given in the article that follows. Python is a computer language that can perform more tasks than other languages and is...

5 minutes read.

Spyder (32-bit) - Free download

Spyder is a free and open-source scientific environment created by and for Python engineers, scientists, and data analysts. It is a robust scientific environment created in Python by and for...

3 minutes read.

Python String rindex() method

Python String rindex() method The string. rindex() method in Python returns the highest index of the substring inside the string (if found). If the substring is not found, it raises an...

2 minutes read.

Python List extend() method

Python List extend() method The list.extend() method extends the list by appending all the items from the iterable. Syntax list.extend(iterable) Parameter iterable: It is a required parameter which represents any iterable unlike list, set, tuple, etc. Example 1 # Python...

1 minute read.

List Iteration in Python

In this tutorial, we will learn how to iterate list in Python. List in Python A list is an ordered group of values which includes several kinds of values.A list is a mutable...

3 minutes read.

Read JSON File in Python

JSON refers to the JavaScript Object Notation. It is a Data format used for representing structured data and it is used to transfer and store data. In JSON format, the...

5 minutes read.

Arguments and parameters in Python

Generally, there is a misunderstanding that parameters and arguments, both are the same. But, as a programmer, you need to understand the difference between these two. Parameters: While defining a function, we...

5 minutes read.

Removing the First Character from the String in Python

String The string is the collection of characters. The strings in python are “immutable”; we cannot change a string once they are created. In python, whatever data we take as input...

4 minutes read.

Python enumerate() function

Python enumerate() function The enumerate() function in Python takes a collection (e.g. a tuple) and returns it as an enumerate object. Syntax: enumerate(iterable, start=0) Parameter Iterable:  This parameter represents an iterable object start:    This parameter represents a number defining...

1 minute read.

Method Overloading in Python

Overloading is a capability of a method and operator to behave differently according to the nature of parameters. Overloading is popular because it provides a good number of advantages: Reusability of code.Reduces...

3 minutes read.

Python md5() function

Python md5() function The md5() function in PHP calculates the md5 hash of a string. Syntax md5 ( string $str [, bool $raw_output] ) Parameter str(required)- This parameter specifies the string. raw_output(optional)- This parameter specifies a hex or binary output format: TRUE - Raw 16 character binary...

1 minute read.

Python Lists vs Tuples

The difference between lists and tuples is one of the most frequently asked questions in an interview related to python language. Lists and Tuples are two of Python’s built-in data...

4 minutes read.

Inheritance in Python

Inheritance in Python Object-Oriented Programming provides reusable patterns to the code for restricting the redundancy in development projects. One of the basic principles of Object-Oriented Programming that helps achieve recyclable code...

8 minutes read.

GET and POST requests using Python

‘GET’ and ‘POST’ are two request methods of Hypertext Transfer Protocol (HTTP). What is HTTP? HTTP stands for Hypertext Transfer Protocol. It is a collection of protocols which makes communication between client...

4 minutes read.

Python Program to Print Sum of all Elements in an Array

Python program to print sum of all elements in an array A set of objects stored in contiguous memory locations is referred to as an array. The concept is to keep...

2 minutes read.

Create a Table Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

3 minutes read.

Python Online Compiler

Compose, Run and Offer Python code internet involving OneCompiler's Python online compiler free of charge. It's one of the hearty, highlight-rich web-based compilers for python language, supporting both the adaptations, which...

3 minutes read.

How to Reverse a number in Python?

In Python, conditional statements can be combined with the list() method, slice() method, recursion() method, and other predefined techniques to generate reverse logical functions. The reverse() method is the most...

7 minutes read.