File Handling in Python
File
is collection of information which is stored on disk or drive. File handling is
method to deal with files in system. For example, opening file, reading file,
writing file, closing file, append file etc. To perform some operations with
your file which is stored at your drive you can use some methods. This method
is called as operations of file.
In
Python we can use various functions and modules to handle files on system.
File Handling Methods in Python:
1.
Opening
File:
The
open () function is used to open file in Python. General syntax is as follows,
My_file=open(filename,mode)
Here
filename is the name of file that you want to open and mode is nothing but the
purpose for what you want to open the file.
Following
are some file opening modes,
‘r’ means file will be opened for reading purpose
‘w’ means file will be opened for write purpose
‘a’ means file will be opened for append mode
‘b’
means file will be opened for binary mode
‘t’
means file will be opened for text mode
For
example,
File_object=open(“Filepath”, ”r”)
file =
open("C:\\Users\\Admin\\Desktop\\Python Notes\\file1.txt", 'r')
Here
file is file object created to open the file. open() function is used to open a
file. In open function parenthesis the location of specified file with its
extension is given and then file opening mode ‘r’ is given that means file is
opened for read mode.
Another example,
filepath =
"C:\\Users\\Admin\\Desktop\\Python Notes\\file1.txt"
file=open(filepath,'r')
In
above example first you can store file location in one variable and then this
variable can be passed in file open () function.
2.
Reading from a file:
The
read() is used to read the file contents from file. This method helps you to
read entire file contents which you have opened from a specified location.
General
Syntax to open File at read Mode
with open(‘filename.txt’, ‘r’) as
fileobject:
variable=f.read()
File
is opened by with method and file name is given in parenthesis to open this
file for ‘r’ means read mode. This method is storing in fileobject. Then one
another variable is created to store file contents. The read function is used
to read the file.
For Example,
filepath =
"C:\\Users\\Admin\\Desktop\\Python Notes\\file1.txt"
file=open(filepath,'r')
content=file.read()
print(content)
Output:
jhegbdhfb
kjsdnkfn
alsndlknf
qlkasdlkfn
lqjasdfln
alksdnflkn
a;lsn
Here
File path is stored into filepath variable. The file is opened by using file
path and mode of opening the file is read with file object file object. Then
this file is used for reading purpose with the help of read() function. If you
want to display the file contents then store this process into one another
variable and then by using print() function display the contents of the file.
The
File is also opened for read mode to check the contents of file with the help
of with method as follows
with
open (filepath,'r') as f:
contents=f.read()
print(contents)
Output:
jhegbdhfb
kjsdnkfn
alsndlknf
qlkasdlkfn
lqjasdfln
alksdnflkn
a;lsn
Reading the file with readline():
The
readline() function is used to read a line from file.
By
default readline function will return first line only.
For
example,
filepath =
"C:\\Users\\Admin\\Desktop\\Python Notes\\file1.txt"
file=open(filepath,'r')
content=file.readline()
print(content)
Output:
Jhegbdhfb
To read particular line from file we
can use readlines() function as follows,
filepath =
"C:\\Users\\Admin\\Desktop\\Python Notes\\file1.txt"
file=open(filepath,'r')
content=file.readlines()
line=content[0]
line
Output:
'Hello friends h r uHello friends h r
u, My name is Anthonymy name is Rohanmy name is Rohan'
Read File using Loop:
We can also apply loop to read file.
filepath =
"C:\\Users\\Admin\\Desktop\\Python Notes\\file1.txt"
with open(filepath,'r') as f:
for line in f:
print(line)
Output:
Hello friends h r uHello friends h r
u, My name is Anthonymy name is Rohanmy name is Rohan
3.
Writing To a File:
To
write new contents to a file you can use write() function. To write something
to a file first file should be opened.
The
general syntax to open file for write mode is as follows,
File=open(“Filename.txt”,
‘w’)
Here
file is file object where file opening method is stored. Open() method is used
to open file. This method has two parameters one is filename is the name of
file which you want to open and ‘w’ is the mode of opening the file. ‘w’ stands
for write mode. When the specified file is exist it is opened and all the
existing contents are replaced with new contents you write in file.
For
example,
file=open("C:\\Users\\Admin\\Desktop\\Python
Notes\\file1.txt",'w')
file.write("This
is file handling class")
Here
file is opened with write mode. Then the file object is used to write new data
to file. When you add this data to your file1 then original file data will be
replaced with ths new data.
If
you want to see the new data is added or not in given file again you need to
open same file with read mode as follows
file=open("C:\\Users\\Admin\\Desktop\\Python
Notes\\file1.txt",'w')
file.write("This is file
handling class")
file=open("C:\\Users\\Admin\\Desktop\\Python
Notes\\file1.txt",'r')
content=file.read()
print(content)
Output:
'This is file handling class'
Another
method to open file for write mode is as follows,
#
File is opened for write mode
filepath =
"C:\\Users\\Admin\\Desktop\\Python Notes\\file1.txt"
with open(filepath,'w') as f:
f.write("Hello friends h r u")
# file is opened for read mode
with open(filepath,'r') as f:
contents=f.read()
print (contents)
Output:
Hello friends h r u
File
is opened by using with method for write mode. The by using write method the
data is added to your file. And same file is then opened with read mode to
check data is added or not.
Another Example
#
File is opened for write mode
filepath
= "C:\\Users\\Admin\\Desktop\\Python Notes\\file11.txt"
with
open(filepath,'w') as f:
f.write("This is Python Class\nToday's
session is File handling session\nThis is demonstration of file opening with
write mode\n")
with
open(filepath,'r') as f:
contents=f.read()
Output:
print
(contents)
This
is Python Class
Today's
session is File handling session
This
is demonstration of file opening with write mode
Here
file11.txt does not exist on a specified
location. When this file is opened with write mode and with the write() method
new data is added then compiler has created new file11.txt on given specified
location. This file is again opened at read mode and with the read() function
this file data is displayed on screen.
4. Append
To a File:
The append() is used to
add new data to existing file without overwriting or replacing the old data or
existing data. When you open file with append mode then new data which you
write will be added at the end of the existing file rather than replace it.
General syntax to open
file at append mode is as follows,
file=open(“Filename.txt”,”a”)
file.write(“New data”)
Here filename.txt is the
name of file which is opened at ‘a’ means append mode. Then new data is added
to file with write method. Once you complete the writing new data you have to
open your file with read mode and read function you can display the contents
from your file.
For example,
# File opend at append
mode
file=open("C:\\Users\\Admin\\Desktop\\Python
Notes\\files.txt",'a')
file.write("\nHello
friends how are you")
file=open("C:\\Users\\Admin\\Desktop\\Python
Notes\\files.txt",'r')
contents=file.read()
print(contents)
Output:
Hello friends how are you
Another example by using
with method,
#file is opened with
apend mode to apend the contents in original file
filepath =
"C:\\Users\\Admin\\Desktop\\Python Notes\\files1.txt"
with open(filepath,'a')
as f:
f.write("Hello friends h r u, My name
is Anthony\n"
"how are you\n"
"here is example of file
handling")
# File is oepned in read
mode to check contents are added in file or not
with open(filepath,'r')
as f:
contents=f.read()
print(contents)
Output:
Hello friends h r u, My
name is Anthony
how are you
here is example of file
handling
Difference Between Write () and append() in Python
In Python, the write() and append() functions are used to write content to files, but they have different behaviors:
1. write() Function:
The write() function is used to write content to a file, starting from the beginning.If the file already exists, using write() will overwrite its content.
If the file does not exist, a new file will be created.
It does not automatically add a newline character (\n) at the end of the written content.
It does not change the file pointer's position after writing.
2. append() Function:
The append() function is used to append content to the end of a file.
If the file does not exist, it will be created.
If the file already exists, using append() will add content to the end of the existing content, without overwriting it.
It automatically adds a newline character (\n) at the end of the appended content.
It changes the file pointer's position to the end of the file after appending.
Opening File in Bothe Read and Write
Method with ‘r+’ or Method
To
open file for read and write both the mode you can use ‘r+’ method method. But when you want to apply read write mode on your file means you want to read and write to the file so remember your file should be exist on you disk otherwise FileNotFoundError will occur.
Example
to open file at read and write mode,
filepath
= "C:\\Users\\Admin\\Desktop\\Python Notes\\file.txt"
with
open(filepath,'r+') as f:
contents=f.read()
f.write("\nmy name is Rohan\n")
print(contents)
Output:
ksjhdfkg
alsndfkna
asjdlfkjl
asjdflkj
aklsdlfn
asdlkfnmy
name is Rohanmy name is Rohan
my
name is Rohan
The
file.txt is already available on disk so it can be open for both read and write
mode. ‘r+’ means file is opened for read and write mode.
5. Closing
The File:
When everything is done
with file then your file should be closed. You can close the opened file with
close() method. This method ensures that every changes you made with your file
are saved to you file and your file is saved with new changes on disk.
General
Syntax,
file.close()
For
Example,
filepath
= "C:\\Users\\Admin\\Desktop\\Python Notes\\file.txt"
file=open(filepath,'r')
content=file.read()
print(content)
file.close()
Here file.txt is opened
at read mode and contents are displayed on screen. The same file is closed with
close() method.
Renaming The File:
In Python files are
removed with ‘OS’ module. The OS module can provide rename() function can be
used to rename your file. The rename() method take two arguments one is old
file name and second is new file name.
Following is example to
use rename() method
import os
oldfile="C:\\Users\\Admin\\Desktop\\Python
Notes\\file.txt"
newfile="C:\\Users\\Admin\\Desktop\\Python
Notes\\renamed.txt"
os.rename(oldfile,newfile)
Here oldfile is a file
which is available on disk with this specified location. On the same location
this old file is renamed and store on disk. To rename your existing file which
is present on your disk first you have to import the os module. The with the help rename() method of os module
the old file is renamed with new file.
Deleting the File:
To delete file in Python
you can use os module. From the os
module remove() method is used to to remove the existing file from the disk.
For example,
import os
filepath="C:\\Users\\Admin\\Desktop\\Python
Notes\\file111.txt"
os.remove(filepath)
To remove file from a
specified location first you must import os module.
From the os module use
remove() to remove the specified file. In above example file111.txt is a text
file available on given location. This file is removed from disk permanently
from disk with the help of remove(). You can check your file on disk. Or you
can open this file at red mode to check this file is available or not.
filepath="C:\\Users\\Admin\\Desktop\\Python
Notes\\file111.txt"
file=open(filepath,'r')
content=file.read()
print(content)
Error:
FileNotFoundError: [Errno 2] No such file or
directory: 'C:\\Users\\Admin\\Desktop\\Python Notes\\file111.txt'
0 टिप्पण्या
कृपया तुमच्या प्रियजनांना लेख शेअर करा आणि तुमचा अभिप्राय जरूर नोंदवा. 🙏 🙏