Python_9
Python_9
Today you'll learn how to work with files in Python—reading from and writing to files—which is a
crucial skill for handling external data, logging, configuration management, and more. We'll cover
the basics of file operations, file modes, and best practices for working with files.
• Definition:
File I/O (Input/Output) refers to the operations of reading from and writing to files on your
computer's storage.
• Why It Matters:
o Data Persistence: Save and retrieve data even after your program ends.
o Data Processing: Read logs, process text data, and work with CSV or JSON files.
Opening a File
• Function: open()
• Syntax:
• Common Modes:
o "w": Write mode. Opens the file for writing (creates a new file or truncates an existing
one).
o "a": Append mode. Opens the file for appending (adds data at the end without
truncating).
o "r+": Read and write mode. Opens the file for both reading and writing.
Closing a File
• Method: .close()
• Why:
Always close a file after you're done to free up system resources.
• Example:
file.close()
• Preferred Way:
Using the with statement automatically handles closing the file.
• Example:
data = file.read()
1. read():
Reads the entire file as a single string.
content = file.read()
print(content)
2. readline():
Reads one line at a time.
first_line = file.readline()
print(first_line)
3. readlines():
Reads all lines and returns them as a list.
lines = file.readlines()
print(lines)
1. write():
Writes a string to the file. Use "w" mode to create/truncate a file or "a" mode to append.
2. writelines():
Writes a list of strings to the file.
file.writelines(lines)
Task:
• Create a text file named sample.txt with some sample content (e.g., multiple lines of text).
• Write a script to open the file, read its content, and print it to the console.
Sample Code:
content = file.read()
Task:
Sample Code:
lines = [
file.writelines(lines)
# Read back and print the content
data = file.read()
Task:
• Write a script that appends a new line to an existing file (or creates a new file if it doesn't
exist) using append mode ("a").
Sample Code:
updated_data = file.read()
python
print(f.read())