×

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

Convert int to Float in Python using Pandas

Introduction We have already learnt about how to convert float variables to int. Now let us know how to convert int variables to float So let us create another Dataset on which...

2 minutes read.

Python id() function

Python id() function The id() function in Python returns an id for the specified object where all the objects in has its own unique id. Syntax id(object) Parameter object: This parameter represents any object, String, Number, List,...

1 minute read.

List Assignment Index out of Range in Python

As we know, a List is one of the four unique data structures available in Python; In this tutorial, we will deep dive into understanding iterating through a list and...

3 minutes read.

Python Functionalities of Pillow Module

This instructional exercise is about "Pillow" library, one of the significant libraries of python for picture control. Pillow library of python, is an easy to use and also open source...

14 minutes read.

How To Compare Two Strings In Python

In this article, we will discuss how to compare two strings in Python. So, before that, let’s have a quick revision on “What are strings?” Strings are a sequence of characters that...

5 minutes read.

Python Static Method

Introduction to methods that are majorly used in Python: Class MethodsInstance MethodsStatic Methods Before going to the in-depth concept of Static Methods, let us briefly discuss Class Methods and Instance Methods. Class Methods The...

4 minutes read.

Python eval() function

Python eval() function The eval() function in Python is used to evaluate the given expression. If the specified expression is a legal Python statement, it will be executed. Syntax eval(expression, globals=None, locals=None) Parameter expression: This parameter represents a String,...

1 minute read.

Python vs HTML

Python and HTML are not comparable since they are two separate categories of programming languages. Building the structures and layouts of a web page or app requires the usage of HTML,...

8 minutes read.

Python getattr() function

Python getattr() function The getattr() function in Python returns the value of the named attribute for the given object. Syntax getattr(object, name[, default]) Parameter object: It is a required parameter which represents an object. name: This parameter represents the...

1 minute read.

Python Time Library

We will consider various functions given by the python module library with examples.This python time module helps to work on time in python to get the current time.Before going with...

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.

How to Pass a list as an Argument in Python

Lists in Python A list is a datatype in python which is used to store the data in a sequence. The lists are mutable; that is, we can change the values...

3 minutes read.

How to comment out a block of code in Python

When you are writing code in Python, you may want to document it. You need to mention why a piece of code functions, for instance. Mathematics, algorithms, and intricate business...

4 minutes read.

SKLearn Model Selection

The model selections of SK learn has many functions with which we can work on.It has functions to cross-validate the model and, it also provides validation and learning curves.It is...

3 minutes read.

How To Install Python In Ubuntu

How To Install Python In Ubuntu Ubuntu is free and open-source software and it is an essential part of the Linux distribution. It is a popular operating system developed by Canonical. If we...

3 minutes read.

Executing Shell Commands in Python

This tutorial aims to make us understand what a Shell is, what is the importance of a Shell, what are Shell commands in Python, and how can we execute the...

3 minutes read.

Python lambda() Function

In this tutorial, we will learn about a new concept known as the Lambda function. It is a relatively new concept while learning Python. Python lambda functions are anonymous functions. It...

3 minutes read.

How to Print Pattern in Python

How to Print Pattern in Python. Pattern programs are really important for beginners and they are always asked in all the technical interviews. Multiple loops approach is used to print the different...

6 minutes read.

Find Median of List in Python

The median is an enlightening measurement that is utilized as a proportion of the focal inclination of a circulation. It is equivalent to the centre worth of the conveyance. There...

3 minutes read.

Comment starts with the symbol in Python

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

3 minutes read.