StudyLover
  • Home
  • Study Zone
  • Profiles
  • Typing Tutor
  • Contact us
  • Sign in
StudyLover File Handling
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
Void functions and Fruitful Functions : File handling functions
Unit 3: Getting Started with Python: A Guide to Syntax, Data Structures, and OOP

File Handling is the process of working with files on your computer's storage system. It allows your Python programs to read data from files (like configuration files, logs, or user data) and write data to files (like saving results, creating reports, or logging events). This is essential for making your programs persistent, meaning they can save their state and data even after the program has finished running.

1. Opening a File: The open() Function

The first step in file handling is always to open the file. This is done using the built-in open() function, which returns a file object. The function takes two main arguments: the file path and the mode.

The mode is a string that specifies the purpose for which you are opening the file:

  • 'r' - Read (default): Opens a file for reading. An error occurs if the file does not exist.

  • 'w' - Write: Opens a file for writing. It creates a new file if it does not exist, or overwrites the entire contents of the file if it does exist.

  • 'a' - Append: Opens a file for appending. New data is added to the end of the file. It creates a new file if it does not exist.

  • 'x' - Create: Creates the specified file. An error occurs if the file already exists.

  • You can also add '+' to a mode (e.g., 'r+') to open it for both reading and writing.

Python

# --- Opening a file in write mode ---

# This will create 'my_file.txt' if it doesn't exist, or overwrite it if it does.

file_object = open('my_file.txt', 'w')

 

# It is crucial to close the file after you are done with it to free up resources.

file_object.close()

print("File 'my_file.txt' was opened and closed.")


2. The with Statement (Recommended Practice)

Manually calling .close() can be problematic because if an error occurs while the file is open, the .close() line might never be reached. The modern and recommended way to handle files is using the with statement. It automatically takes care of closing the file for you, even if errors occur.

  • Use Case: This should be your default method for working with files to ensure they are always closed properly.

Python

# --- Using the 'with' statement ---

# The file is automatically closed when the indented block is exited.

try:

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

        f.write("This is a safe way to handle files.\n")

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

   

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

except Exception as e:

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


3. Writing to Files

Once a file is open in 'w' (write) or 'a' (append) mode, you can write data to it.

  • .write(string): Writes a single string to the file. You must include newline characters (\n) manually if you want to write on separate lines.

  • .writelines(list_of_strings): Writes all the strings from a list (or any iterable) to the file. It does not add newline characters between the strings.

Python

# --- Writing to a file ---

lines_to_write = ["First line.\n", "Second line.\n", "Third line.\n"]

 

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

    # Using .write()

    f.write("This is the report header.\n")

    f.write("-------------------------\n")

   

    # Using .writelines()

    f.writelines(lines_to_write)

 

print("File 'report.txt' has been written.")


4. Reading from Files

Once a file is open in 'r' (read) mode, you can read its contents.

  • .read(): Reads the entire content of the file and returns it as a single string.

  • .readline(): Reads a single line from the file, including the newline character at the end. Each time you call it, it reads the next line.

  • .readlines(): Reads all the lines in the file and returns them as a list of strings.

  • Iterating over the file object: This is the most common and memory-efficient way to read a file line by line.

Python

# --- Reading from a file ---

# First, let's make sure the file exists by writing to it.

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

    f.write("Line 1\nLine 2\nLine 3\n")

 

print("--- Reading the whole file with .read() ---")

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

    content = f.read()

    print(content)

 

print("--- Reading line by line with a for loop (recommended) ---")

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

    for line in f:

        # .strip() removes leading/trailing whitespace, including the newline character

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


5. Appending to Files

Appending adds new content to the end of an existing file without deleting its current content.

  • Use Case: This is perfect for tasks like logging, where you want to add new entries to a log file over time without erasing the old ones.

Python

# --- Appending to a file ---

# First, create or overwrite the log file.

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

    f.write("Log started.\n")

 

# Now, open it in append mode to add more content.

with open('app_log.txt', 'a') as f:

    f.write("User logged in.\n")

    f.write("Data processed successfully.\n")

 

print("Appended new entries to 'app_log.txt'.")

 

# Let's read the file to see the result

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

    print("\n--- Contents of app_log.txt ---")

    print(f.read())


6. Moving the Cursor: .seek() and .tell()

File objects have an internal cursor that keeps track of where you are in the file.

  • .tell(): Returns the current position of the cursor (as an integer number of bytes).

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

  • Use Case: For non-text files or when you need to read or overwrite specific parts of a file without processing the whole thing.

Python

# --- Using .seek() and .tell() ---

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

    f.write("Hello, World!")

 

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

    # Read the first 5 characters

    print(f.read(5)) # Output: Hello

   

    # Check the cursor position

    print(f"Cursor is at position: {f.tell()}") # Output: 5

   

    # Move the cursor back to the beginning

    f.seek(0)

    print("Cursor moved back to the beginning.")

   

    # Read the whole file again

    print(f"Full content: {f.read()}") # Output: Hello, World!

 

Void functions and Fruitful Functions File handling functions
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