StudyLover
  • Home
  • Study Zone
  • Profiles
  • Typing Tutor
  • Contact us
  • Sign in
StudyLover File handling functions
Download
  1. Python
  2. Pyhton MCA (Machine Learning using Python)
  3. Unit 3: Getting Started with Python: A Guide to Syntax, Data Structures, and OOP
File Handling : Object Oriented concepts
Unit 3: Getting Started with Python: A Guide to Syntax, Data Structures, and OOP

File Handling is the process of using your program to read from and write to files on your computer's storage. This is essential for any application that needs to save data, load configuration, or create logs. The primary tool for this is Python's built-in open() function, which creates a "file object" that has various methods for interaction.

1. The open() Function

This is the main function used to open a file. It returns a file object that you can then use to perform operations. The most important arguments are the file's path and the mode in which you want to open it.

  • Use Case: The first step for any file interaction, whether you intend to read, write, or append.

The primary modes are:

  • 'r': Read (default). Opens for reading. Fails if the file doesn't exist.

  • 'w': Write. Opens for writing. Overwrites the entire file if it exists, or creates a new one if it doesn't.

  • 'a': Append. Opens for writing. Adds new content to the end of the file. Creates a new file if it doesn't exist.

  • 'x': Create. Exclusively creates a new file. Fails if the file already exists.

  • '+': Can be added to a mode (e.g., 'r+') to allow for both reading and writing.

Python

# --- open() and close() Example ---

# Open a file in write mode, which creates it.

try:

    file = open('example.txt', 'w')

    # It's crucial to close the file to save changes and free up resources.

    file.close()

    print("File 'example.txt' created and closed successfully.")

except Exception as e:

    print(f"An error occurred: {e}")


2. The with Statement (Context Manager)

This is the modern and highly recommended way to work with files. It automatically handles closing the file for you, even if errors occur within the block.

  • Use Case: This should be your standard practice for all file handling to ensure resources are managed correctly and to make your code cleaner and safer.

Python

# --- 'with' Statement Example ---

try:

    with open('example.txt', 'w') as f:

        print("Inside 'with' block: File is open.")

        f.write("Hello, World!")

    # The file is automatically closed once the block is exited.

    print("Outside 'with' block: File is now closed.")

except Exception as e:

    print(f"An error occurred: {e}")


3. Writing Methods

.write(string)

Writes a single string to the file. You must manually add newline characters (\n) if you want to start a new line.

Use Case: Writing a single line of text, a header, or building a file piece by piece.

Python

# --- .write() Example ---

with open('log.txt', 'w') as f:

    f.write("Log Entry 1: System started.\n")

    f.write("Log Entry 2: User logged in.\n")

print("Wrote two lines to log.txt.")

.writelines(list_of_strings)

Writes all the strings from an iterable (like a list) to the file. It does not add newline characters automatically.

  • Use Case: Efficiently writing a pre-existing list of lines to a file.

Python

# --- .writelines() Example ---

lines = ["First line\n", "Second line\n", "Third line\n"]

with open('report.txt', 'w') as f:

    f.writelines(lines)

print("Wrote a list of lines to report.txt.")


4. Reading Methods

.read()

Reads the entire content of the file and returns it as a single string.

  • Use Case: Reading a small file into memory all at once, for example, a configuration file. Be cautious with large files as this can consume a lot of memory.

Python

# --- .read() Example ---

with open('report.txt', 'r') as f:

    content = f.read()

    print("--- Full content of report.txt ---")

    print(content)

.readline()

Reads a single line from the file, including the trailing newline character. Each subsequent call reads the next line.

  • Use Case: Reading a large file line by line in a memory-efficient way, especially when you only need to process one line at a time.

Python

# --- .readline() Example ---

with open('report.txt', 'r') as f:

    line1 = f.readline().strip() # .strip() removes the newline character

    line2 = f.readline().strip()

    print(f"First line: {line1}")

    print(f"Second line: {line2}")

.readlines()

Reads all the lines in the file and returns them as a list of strings, with each string ending in a newline character.

  • Use Case: When you need to have all lines of a file in a list for processing, such as sorting them or accessing them by index.

Python

# --- .readlines() Example ---

with open('report.txt', 'r') as f:

    all_lines = f.readlines()

    print(f"Lines as a list: {all_lines}")

Iterating over the File Object

This is the most common, readable, and memory-efficient way to process a file line by line.

  • Use Case: The standard way to read and process any text file, regardless of its size.

Python

# --- Iteration Example ---

print("\n--- Iterating through the file ---")

with open('report.txt', 'r') as f:

    for line in f:

        print(f"Processing line: {line.strip()}")


5. Cursor Manipulation Methods

File objects have an internal cursor that keeps track of your position.

.tell()

Returns the current position of the cursor as an integer (number of bytes from the beginning of the file).

  • Use Case: To save your current position in a file so you can return to it later.

Python

# --- .tell() Example ---

with open('report.txt', 'r') as f:

    f.readline() # Read the first line

    current_position = f.tell()

    print(f"Cursor is at byte position: {current_position}")

.seek(offset)

Moves the cursor to a specific byte position (offset) in the file.

  • Use Case: To jump to a specific part of a file without reading all the content before it. For example, jumping back to the beginning (f.seek(0)).

Python

# --- .seek() Example ---

with open('report.txt', 'r') as f:

    content = f.read()

    print(f"Read once: '{content.strip()}'")

   

    print("Moving cursor back to the start...")

    f.seek(0) # Go back to the beginning of the file

   

    content_again = f.read()

    print(f"Read again: '{content_again.strip()}'")

 

File Handling Object Oriented concepts
Our Products & Services
  • Home
Connect with us
  • Contact us
  • +91 82955 87844
  • Rk6yadav@gmail.com

StudyLover - About us

The Best knowledge for Best people.

Copyright © StudyLover
Powered by Odoo - Create a free website