LA ILAHA ILLA HU
Allah, Your Lord There Is No Deity Except Him.
Python Data Science File Handling In Python: Open File
As file handling is an important part of any web application.
Python has several functions for creating, reading, updating, and deleting files.
How to open a file?
The open() function: the open() function is key function for working with files in Python.
It takes two parameters.
1. filename.
2. mode.
There are four different methods (modes) for opening a file in Python.
1. "r" - Read
Default value. Opens a file for reading, error if the file does not exist.
2. "a" Append
Opens a file for appending, creates the file if it does not exist.
3. "w" Write
Opens a file for writing, creates the file if it does not exist.
4. "x" Create
Creates the specified file, returns an error if the file exists.
In addition to the above you can specify if the file should be handled as binary or text mode.
"t" - Text - Default value. Text mode.
"b" - Binary - Binary mode (e.g. images).
Syntax: To open a file for reading it is enough to specify the name of the file
f = open("demofile.txt")
The code above is the same as.
f = open("demofile.txt", "rt")
Where "r" stands for read, and "t" for text are the default values.You do not need to specify them.
Example 1: Read a text file.
Code
f = open("example.txt",
"r")
print(f.read())
the output will be
ILLUSTRATION This is Line 2. This is Line 3. This is Line 4. This is Line 5.Output will vary depending upon your file.
How to read an image file.?
We have a google badge image saved on our pc, the name of the file is badge.png in order to read this image we will follow the code lines in the example below.
How to read an image file in Python.?
Example 1-B: Read an image file.
Code
# Imports PIL module
from PIL import Image
# used to open different extension image file
im = Image.open
("badge.png")
# shows image in any image viewer
im.show()
the output will be
Note
In order to read an image you will have to import PIL module.
If you do not have PIL already install you can install it with the following command.
pip Install PIL
Writing the above line in the terminal and pressing enter will install PIL on your system.