File Handling: Reading and Writing Files
File handling is a crucial aspect of programming as it allows programs to read from and write to files, enabling data persistence. Python provides built-in functions and methods to perform file operations, including reading, writing, and closing files. This module covers the basic file operations, working with text and binary files, and managing file states.
Subtopic 1: Understanding File Operations
File operations allow you to interact with files on your computer. The most common operations include opening, reading, writing, and closing files. In Python, the open() function is used to access a file, and it returns a file object.
File Operations Overview:
- Opening a file: Before you can read from or write to a file, you must open it using the
open()function. - Reading from a file: You can read the contents of a file using methods like
read(),readline(), andreadlines(). - Writing to a file: You can write data to a file using methods like
write()andwritelines(). - Closing a file: It's important to close a file after you're done with it to ensure that the data is properly saved and resources are released.
Subtopic 2: Opening and Closing Files
To open a file, you use the open() function. This function requires at least one argument, the filename, and optionally a mode argument that specifies whether you want to read, write, or append to the file.
Syntax:
file_object = open('filename', 'mode')
Common Modes:
'r': Read (default mode, opens the file for reading).'w': Write (opens the file for writing, creates a new file if it doesn't exist).'a': Append (opens the file for writing, appends to the end of the file).'b': Binary mode (used for binary files).'x': Exclusive creation (creates a new file, returns an error if the file exists).
Example:
file = open('example.txt', 'w') # Open file in write mode
file.write("Hello, World!") # Write data to the file
file.close() # Close the file
It's important to always close a file after performing operations to release resources. The close() method is used for this purpose.
Example with with Statement (Context Manager):
Using with ensures that the file is automatically closed after the operations are completed, even if an exception occurs.
with open('example.txt', 'w') as file:
file.write("Hello, World!")
# File is automatically closed here
Subtopic 3: Reading and Writing Text Files
Once a file is open, you can read or write data to it. There are different methods for reading data depending on your needs.
Reading from a File:
read(): Reads the entire content of the file.readline(): Reads one line from the file.readlines(): Reads all lines into a list.
Example: Reading a File
with open('example.txt', 'r') as file:
content = file.read()
print(content)
Writing to a File:
write(): Writes a string to the file.writelines(): Writes a list of strings to the file.
Example: Writing to a File
with open('example.txt', 'w') as file:
file.write("This is a test.\n")
file.write("Writing to a file is easy!")
Example: Writing Multiple Lines
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open('example.txt', 'w') as file:
file.writelines(lines)
Subtopic 4: Working with Binary Files
Binary files store data in binary format (as opposed to plain text). You can open binary files in Python by using the 'b' mode when opening the file.
Common Binary File Operations:
- Reading binary data:
read()can be used to read binary files. - Writing binary data:
write()can be used to write binary data.
Example: Reading a Binary File
with open('example_image.jpg', 'rb') as file:
content = file.read()
print(content[:100]) # Print first 100 bytes
Example: Writing to a Binary File
data = b'\x89PNG\r\n\x1a\n' # Example binary data (PNG header)
with open('output_image.png', 'wb') as file:
file.write(data)
Tasks
-
Task 1: Reading a Text File
- Write a Python program that opens a text file, reads its contents, and prints them line by line.
-
Task 2: Writing to a Text File
- Create a program that asks the user for a message, then writes that message to a text file. Afterward, open the file and read the content to verify it was written correctly.
-
Task 3: Appending Data to a File
- Write a Python script that opens a file in append mode, adds some new content to the file, and then displays the updated file contents.
-
Task 4: Working with Binary Files
- Write a Python program to read and display the first 100 bytes of a binary file (e.g., an image or audio file).
-
Task 5: Copying a File
- Write a Python program that copies the content of one text file into another, preserving the content.
-
Task 6: Handling Non-Existing Files
- Modify your program to handle situations where a file does not exist when attempting to read or write, and display a meaningful error message.