Skip to main content

File Handling in Python

 


What is File Handling?

·         File Handling refers to the ability of a program to work with files, which are external resources that can be used to store data or information.

·         File handling can be used to create, read, write, append, and delete files, among other things.

 

Opening and Closing Files

·         To open a file in Python, we use the built-in open() function.

·         The open() function takes two arguments:

o    the name of the file to be opened,

o    the mode in which the file is opened.

·         Syntax

file_object = open(file_name, mode)

       The modes available for opening a file are:

·         r: Read mode. This is the default mode. It opens the file for reading. If the file does not exist, it will raise an error.

·         w: Write mode. It opens the file for writing. If the file does not exist, it creates a new file. If the file already exists, it truncates the file.

·         a: Append mode. It opens the file for writing. If the file does not exist, it creates a new file. If the file already exists, it appends the data to the end of the file.

·         x: Exclusive mode. It opens the file for writing. If the file already exists, it raises an error.

·         t: Text mode. It opens the file in text mode. This is the default mode.

·         b: Binary mode. It opens the file in binary mode.

 

·         Example:

To open a file named "example.txt" in read mode:

file_object = open("example.txt", "r")

·         To close a file in Python, we use the built-in close() method.

Reading from Files

·         To read the contents of a file in Python, we use the read() method.

·         The read() method reads the entire file as a single string.

·         Alternatively, we can use the readline() method to read one line at a time, or the readlines() method to read all the lines into a list.

·         Example:

file_object = open("example.txt", "r")

file_contents = file_object.read()

print(file_contents)

file_object.close()

In the above example, we open the file in read mode and read its contents using the read() method. We then print the contents of the file and close the file using the close() method.

 

Writing to Files

·         To write to a file in Python, we use the write() method.

·         The write() method writes a string to the file.

·         When using the write mode, the entire contents of the file are overwritten with the new data. To avoid overwriting, use the append mode.

·         Example:

file_object = open("example.txt", "w")

file_object.write("Hello, Python Experts")

file_object.close()

In the above example, we open the file in write mode and write the string "Hello, Python Experts" to the file using the write() method. We then close the file using the close() method.

 

Appending to a File:

·         To append to a file, we must first open the file in append mode.

·         We can then use various methods to append to the file. The most commonly used method is the write() method.

·         The write() method writes the specified string to the end of the file.

·         Example:

file_object = open("example.txt", "a")

file_object.write("\nWelcome to file handling in Python!")

file_object.close()

 

Some implications of using different modes when opening files:

 

·         Read mode (r): You can read data from an existing file but cannot write to it. If the file does not exist, an error will occur.

·         Write mode (w): You can write data to a file, but its contents will be truncated if the file already exists. If the file does not exist, a new file will be created. It's important to note that if you open a file in write mode and then try to read from it, an error will occur.

·         Append mode (a): You can append data to an existing file, but cannot overwrite its contents. If the file does not exist, a new file will be created.

·         Exclusive creation mode (x): You can create a new file, but the operation will fail if the file already exists.

·         Binary mode (b): This mode is used for opening binary files, such as images or executables. When opening a binary file, you should specify the mode as rb or wb.

·         Text mode (t): This mode is used for opening text files, such as .txt or .csv files. When opening a text file, you should specify the mode as rt or wt.

 

Some of other File Handling methods:

To Rename a File:

 

import os

os.rename(current_file_name, new_file_name)

 

To delete a file:

import os

os.remove(file_name)

 

 

To copy a File:

import shutil

src_path = '/path/to/source/file.txt'

dst_path = '/path/to/destination/file.txt'

shutil.copy(src_path, dst_path)

 

To move a File:

                shutil.move(src_path, dst_path)

 

To List a Dir:

                dir_list = os.listdir(path)

 

To check the directory exists or not:

                os.path.isdir( path )


 

Methods for Random Access to Files in Python

 

Python provides several methods for random access to files. Here are some of the most commonly used methods:

 

The seek() Method:

The seek() method is used to move the file pointer to a specific position in the file. This method takes one argument, which specifies the position in the file to which the pointer should be moved. The position is specified in bytes, starting from the beginning of the file.

 

Syntax:

file.seek(offset, whence)

where,

·         The offset parameter specifies the number of bytes to move the file pointer. The whence parameter specifies the reference position from which to move the file pointer.

·         The possible values for whence are:

0: the beginning of the file (default)

1: the current position in the file

2: the end of the file

 

Example:

f = open("file.txt", "rb")

f.seek(10) # move the file pointer to position 10

data = f.read(5) # read 5 bytes of data from position 10

print(data)

f.close()

 

The tell() Method:

The tell() method is used to get the current position of the file pointer in the file. This method takes no arguments and returns the current position of the file pointer in bytes, starting from the beginning of the file.

Example:

f = open("file.txt", "rb")

pos = f.tell() # get the current position of the file pointer

print(pos)

f.close()

 

The read() Method:

The read() method is used to read a specified number of bytes from the file, starting from the current position of the file pointer. This method takes one argument, which specifies the number of bytes to read.

Example:

f = open("file.txt", "rb")

data = f.read(10) # read 10 bytes of data from the file

print(data)

f.close()

 

The write() Method:

The write() method is used to write data to a file at a specified position. This method takes two arguments: the data to be written, and the position in the file to which the data should be written.

Example:

f = open("file.txt", "wb")

f.write(b"Hello World!") # write the string "Hello World!" to the file

f.close()

 

The readline() Method:

The readline() method is used to read a single line of text from the file, starting from the current position of the file pointer. This method takes no arguments and returns a string that contains the line of text.

Example:

f = open("file.txt", "r")

line = f.readline() # read a single line of text from the file

print(line)

f.close()

 

The writelines() Method:

The writelines() method is used to write a sequence of strings to a file. This method takes one argument, which is a sequence of strings to be written to the file.

Example:

f = open("file.txt", "w")

lines = ["Hello\n", "World\n"]

f.writelines(lines) # write the sequence of strings to the file

f.close()

 

 

Activities:

1.       Read a list of numbers from a file and find sum, average, maximum and minimum value

2.       Get the sentence using console and write / append into a file

3.       Read the text (paragraph or sentence) from a file and Replace a particular string (word) with new string (Ex. Replace the words hello with hi)

4.       Read the text from file and count number of characters, words, vowels and consonants.

Comments

Popular posts from this blog

Python OOPs Concepts: Using Variables and Methods

  Types of Variables in OOPs Python   Instance Variable Static Variable Local Variable   Object Level Variables Class Level Variables Method Level Variables When to use: For Every Object if you want Separate copy, use Instance Variables For all object one copy is required, use static variables Inside method, Just used for temporary requirement Where to Declare Inside the constructor method (in general) Within the class directly, outside of methods (in general)   Within the method only. How to Declare Within the constructor: Instance variables can be declared within the constructor method using the self .   Using default values : Instance variables can be assigned default values during initialization.   Outside the class: use object name.   ·          Within the class directly

Inheritance

Inheritance is a fundamental concept in object-oriented programming, which allows a class to inherit properties and methods from another class. There are several types of inheritance, including: Single Inheritance: In single inheritance, a subclass inherits properties and methods from a single parent class. The subclass is said to be derived from the parent class. Multiple Inheritance: Multiple inheritance allows a subclass to inherit properties and methods from multiple parent classes. In this case, the subclass is said to have multiple base classes. However, multiple inheritance can lead to complexity and ambiguity in the code. Multilevel Inheritance: Multilevel inheritance occurs when a subclass inherits properties and methods from a parent class, which in turn inherits from another parent class. In this case, the subclass is said to be derived from both the parent class and the grandparent class. Hierarchical Inheritance: Hierarchical inheritance occurs when multiple subclasses

Polymorphism: Method Overloading vs Method Overriding

  Method Overloading In object-oriented programming languages, method overloading enables a class to have several methods with the same name but different parameters. However, in Python, method overloading is not directly supported as opposed to languages such as Java or C++. This is because Python allows developers to define default arguments for their methods and pass arguments of any type to a method. This flexibility allows a single method to handle various types of arguments, eliminating the need for overloading.   However, there is a way to simulate method overloading in Python by using default argument values or variable length arguments and conditional statements. Here's an example: Program using default arguments:       Program using variable length arguments:   Multiple methods with Same Name: When we define multiple methods with same name, Python will consider the last defined method only. Python will not support method overloading. ( Why? Method overlo