Open a File in Python
In this tutorial,we will learn how to open a file in python with some cool and easy examples.In many situations,you might have to come up with this type of requirements.
Python provides some inbuilt functions.This can be done using the open() function. It takes two arguments, one is file name and another that accepts the Access Mode.
Syntax to open a file in python:
File_object = open(“File_Name”, “Access_Mode”)
The explanation of syntax:
File_Name=The file that you want to open.
Access_Mode=It describes the mode in which the file will be opened.
If the file is not exist, then an error is generated.The file should exist in the same directory as the Python script, otherwise full address of the file should be written.
Let’s learn this with some easy examples.
file = open("filename.txt","r")
In this example, the file name is “filename.txt” and the mode is “r” which stands for read mode. This means that you can read the contents of the file.
You can also specify different modes depending on what you want to do with the file. Some common modes are:
- “r”: Read mode (default). Opens the file for reading.
- “w”: Write mode. Opens the file for writing.
- “a”: Append mode. Opens the file for appending. If the file does not exist, a new file will be created.
let’s see another example.
filename.txt
Hello! Welcome to filename.txt This file is for testing purposes. Good Luck!
f = open("filename.txt", "r") print(f.read()) f.close()
In the above example we are opening a file i.e filename and the access mode is read.If you run this program it will show the output as:
output:
Hello! Welcome to filename.txt This file is for testing purposes. Good Luck!