Sunday, July 18, 2021

File handling

Python has many functions for file handling.

for any file operation, initially the file must be opened.


open() function opens an existing file.

my_file=open("Sample.txt")  is the syntax to open a file.

open() function takes two parameters.

  1. file name
  2. mode 

mode is the mode in which you want to open the file which can be any of the following.

  • read - r - opens file in reading mode, if file is not present gives error

  • write - w - opens file in writing mode, if file is not present gives error

  • append - a - opens file for appending, if file is not present gives error

  • create - x - creates file, if file is already present gives error

You cannot write into the file if the file is opened in read/append mode.

You cannot perform read operation on the file opened in writing/append mode.

You cannot perform append operation, if the file is opened in read/write mode.

This is my sample.txt file. 

 


 

 

How to read and modify the content in the files 

  • read a file

  • write into a file - write,append

  • close

  • delete

 

1)Reading a file.

in file opened with read mode:

  • read() function reads the entire file.

  • read(15) reads only the first 15 characters in the file.

  • readline() reads the first line in the file.


 

2)Writing into a file.

in a file opened with write mode

write() function rewrites the file with new content.

in a file opened with append mode

write() function appends the new content to end of the file.


 

3)Closing a file.

close() is used to close a file.

when ever the file is read the object will be pointing to end of the file.

So performing read operation again will result in empty string.

Whenever the file is closed the object will point again to the beginning of the file.

 


 

4)Deleting a file.

To delete a file import os module and call remove() function.

import os

os.remove("Sample.txt")

To delete the folder call rmdir() function

import os

os.rmdir("Newfolder")

 

Video explanation :  https://youtu.be/dschu28WCIg


 

 



No comments:

Post a Comment

Anaconda Installation

In this post we will discuss about Anaconda and its installation. Anaconda comes with number of applications(jupyter notebook included), dat...