File: A file is a collection of data stored in an enclosed unit( the data can be text, image etc.), identified by a filename.

File Handling: File handling is the process of applying various operations on the file such as create , update , delete etc.

File Handling in python: Python provides a number of in-built operations to manipulate the files.

Read Files Using Python

syntax: f = open(“file path”, “r”)

if file is in the same location then we have to mention only the name of the file otherwise we have to provide the path to the file.

Example: How to read file

Output:

Another way to read a file is to call a certain number of characters like in the following code the interpreter will read the first five characters of stored data and return it as a string:

Output:

split() using file handling

We can also split lines using file handling in Python. This splits the variable when space is encountered. You can also split using any characters as we wish. Here is the code:

Output:

For loop using file handling

The open command will open the file in the read mode and the for loop will print each line present in the file.

Output:

readlines() using file handling

The open command will open the file in the read mode and the for loop will print each line present in the file.

Output:

Create File Using Python

ways to create a file:

create a empty file

an empty file named fileName is created in the same location

Write Files

There are two ways to write a file :

  1. “a”: It is used to append the content at the end of the file without overwriting the existing content.
  2. “w”: It is used overwrite the existing file and if the file is not created, it will create the file.
  3. write() method is used to append and write to the file.

append to the file

Output:

write to the file:

Output:

Delete File Using Python:

We have to import os module to delete file. “os module” provide two methods remove and rmdir:

methods of os module used in file are:

os.mkdir(): mkdir() method of the os module to create directories in the current directory. You need to supply an argument to this method which contains the name of the directory to be created.

os.chdir(): chdir() method to change the current directory.

os.getcwd(): getcwd() method displays the current working directory.

os.remove(): This method is used to remove or delete a file path but it can not remove or delete a directory.

os.rmdir(): This method is used to remove or delete an empty directory. OSError will be raised if the specified path is not an empty directory.

remove the file:

use os.rmdir() to remove a folder:

checking existing file:

Output: