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.   · ...

ORACLE Express Edition: Getting Started

1. Introduction to Oracle Database 21c Express Edition (XE) - Free, lightweight version of Oracle Database - Ideal for learning and small-scale applications - Limited to 12GB of user data and uses up to 2GB of RAM 2. Installation and Setup 2.1 Installing Oracle 21c XE 1. Download Oracle 21c XE from: https://www.oracle.com/database/technologies/xe-downloads.html 2. Run the installer:    - Windows: Double-click the .exe file    - Linux: Use `rpm` or `yum` command 3. Follow the installation wizard:  Accept the license agreement Choose an installation location (default is usually fine) Set a password for the SYS, SYSTEM, and PDBADMIN accounts (write this down!) Select the option to start the database service automatically (recommended)  4. Complete the installation: Wait for the installation process to finish Note down the database connection details provided at the end The default container database (CDB) name is XE The default pluggable database (PDB) nam...

Practical 1: Getting Started with MYSQL

 Getting Started with MySQL Introduction to MySQL Definition: MySQL is an open-source relational database management system (RDBMS) Uses: Web applications, data warehousing, e-commerce, logging applications Key features: Speed, reliability, scalability, and ease of use Installing MySQL Download MySQL Community Server from official website Follow installation wizard for your operating system Set root password during installation Verify installation: mysql --version MySQL Command-line Client Accessing MySQL: mysql -u root -p Basic commands: SHOW DATABASES ; CREATE DATABASE mydb ; USE mydb ; SHOW TABLES ; MySQL Workbench Introduction: Visual tool for database design and management Key features: SQL development Data modeling Server administration Example: Creating a new connection New Connection > Enter details (hostname, username, password) PHPMyAdmin Web-based MySQL administration tool Often comes pre-installed with web hosting packag...