Python File Operation | File Handling In Python (With Examples)

 PYTHON I/O FILE HANDLING:

File handling in Python involves working with files to read or write data. The io module provides various classes and functions for performing input and output operations on files. 

reload | diplomawaale.blogspot.com
Python I\O File Handling



File handling in Python with the `io` module involves managing files for reading and writing data. Using the `open()` function, you can open files in different modes ('r' for reading, 'w' for writing, 'a' for appending, etc.). Methods like `read()`, `readline()`, and `readlines()` allow you to retrieve content from files, while `write()` and `writelines()` facilitate writing. Utilizing the `with` statement ensures proper file closure. Binary mode ('rb', 'wb') enables working with non-text files. Additionally, exceptions such as `FileNotFoundError` must be handled using `try` and `except`. Efficient file handling aids data storage, configuration, and data manipulation tasks in programming.

MAIN STEP IN FILE HANDLING:

Opening a File: To perform any file operations, you first need to open the file. You use the open() function to do this. The open() function takes two arguments: the path to the file and the mode in which you want to open it. The modes include:

  • 'r': Read (default mode). Opens the file for reading.
  • 'w': Write. Opens the file for writing. If the file already exists, it truncates it. If the file does not exist, it creates a new one.
  • 'a': Append. Opens the file for writing, but if the file already exists, it appends new content to the end of it.
  • 'b': Binary mode. Used in conjunction with other modes to indicate binary file handling (e.g., 'rb' or 'wb').

EXAMPLE:

                          file = open('example.txt', 'r')  # Opens 'example.txt' in read mode

Sr.No.

Modes & Description

1

r

Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.

2

rb

Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.

3

r+

Opens a file for both reading and writing. The file pointer placed at the beginning of the file.

4

rb+

Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file.

5

w

Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

6

wb

Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

7

w+

Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, create a new file for reading and writing.

8

wb+

Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, create a new file for reading and writing.

9

a

Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

10

ab

Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

11

a+

Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

12

ab+

Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

 


Performing Operations: Once the file is open, you can perform various operations on it. The most common ones are:

  • Reading: Use methods like read(), readline(), or readlines() to retrieve content from the file.
  • Writing: Use the write() method to write content to the file.
  • Appending: Use the write() method with the 'a' mode to append content to the end of the file.

EXAMPLE:

                         content = file.read()  # Reads the entire content of the file
                         line = file.readline()  # Reads a single line from the file
                         lines = file.readlines()  # Reads all lines and returns a list

Closing the File: After performing operations on the file, it's important to close it using the close() method. This releases system resources and ensures that changes are saved to the file. If you forget to close the file, it might lead to unexpected behavior.

EXAMPLE:

                            file.close()  # Closes the file

It's considered good practice to use the with a statement when working with files. The 'with' statement automatically takes care of opening and closing the file, even if an exception is raised.

EXAMPLE:

                         with open('example.txt', 'r') as file:
                               content = file.read()
                               print(content)
                        # File is automatically closed after exiting the 'with' block


THE FILE OBJECT ATTRIBUTES:

Sr.No.

Attribute & Description

1

file.closed

Returns true if file is closed, false otherwise.

2

file.mode

Returns access mode with which file was opened.

3

file.name

Returns name of the file.

4

file.softspace

Returns false if space explicitly required with print, true otherwise.

 EXAMPLE:

                                          # Open the file in read mode
                                          with open('example.txt', 'r') as file:
                                                  # Read the content of the file
                                                  content = file.read()
    
                                                  # Display file object attributes
                                                  print("File Name:", file.name)
                                                  print("File Mode:", file.mode)
                                                  print("Is Closed:", file.closed)
                                                  print("Readable:", file.readable())
                                                  print("Writable:", file.writable())
                                                  print("Seekable:", file.seekable())
    
                                          # Get and print the current file pointer position
                                                  position = file.tell()
                                                  print("Current Position:", position)
    
                                          # Print the content of the file
                                                  print("\nFile Content:\n", content)
    
                                          # After exiting the 'with' block, the file is automatically closed
                                          print("Is Closed:", file.closed)


FILE POSITION:

File position refers to the current location of the file pointer within the file. The file pointer indicates the position from which the next read or write operation will occur. It's important to understand and manage the file position when working with files, especially for tasks like reading specific parts of a file or updating its content.
In Python's file handling, you can use the seek() method to move the file pointer to a specific position within the file. The position is specified in terms of byte offset from the beginning of the file.

EXAMPLE:

                               # Open the file in read mode
                               with open('example.txt', 'r') as file:
                                       # Read the first line
                                       line1 = file.readline()
                                       print("Line 1:", line1)
    
                                      # Get the current position
                                      position = file.tell()
                                      print("Current Position:", position)
    
                                     # Move the file pointer to the beginning of the second line
                                     file.seek(len(line1))
    
                                     # Read the second line
                                     line2 = file.readline()
                                     print("Line 2:", line2)
    
                                    # Get the current position
                                    position = file.tell()
                                    print("Current Position:", position)
    
                                   # Move the file pointer to the beginning of the file
                                   file.seek(0)
    
                                  # Read all lines from the beginning
                                  lines = file.readlines()
                                  print("All Lines:", lines)




Post a Comment

0 Comments