#### Specific Objective
Learn how to read multiple Markdown (`.md`) files from a directory and print their contents to the terminal using Python.
#### Prerequisites
- Basic knowledge of Python programming.
- Python installed on your computer.
- A directory containing `.md` files.
#### Steps to Read and Print .md Files
1. **Access the Directory:**
Use the `os` module to navigate the file system and access the directory containing the `.md` files.
2. **Read Each File:**
Loop through the directory, open each `.md` file, and read its contents.
3. **Print the Contents:**
Display the contents of each file to the terminal.
#### Example Code
Here’s how you can implement the steps in Python:
```python
import os
# Define the directory containing the .md files
directory = 'path/to/directory'
# Iterate over each file in the directory
for filename in os.listdir(directory):
if filename.endswith('.md'): # Check if the file is a .md file
filepath = os.path.join(directory, filename)
with open(filepath, 'r', encoding='utf-8') as file:
content = file.read()
print(f"Contents of {filename}:\n{content}\n")
print("-" * 20) # Print a separator after each file's content
```
#### Common Use Patterns
- **Batch Processing:** This script is useful for batch processing of `.md` files, such as generating summaries or converting formats.
- **Content Aggregation:** Combine it with other tools to aggregate content from various `.md` files into a single document or database.
#### Cheat Sheet
- `os.listdir(directory)`: Lists all files in the specified directory.
- `endswith('.md')`: Checks if a file name ends with `.md`.
- `open(filepath, 'r')`: Opens a file in read mode.
- `file.read()`: Reads the contents of a file.
#### Exercise
1. Create a directory named `markdown_files` on your computer and add a few `.md` files with sample content.
2. Modify the `directory` variable in the script to point to your `markdown_files` directory.
3. Run the script and verify that it prints the contents of all `.md` files in the directory to the terminal.
#### Resources
- Python Documentation on File I/O: [docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files)
- Python Documentation on the OS module: [docs.python.org/3/library/os.html](https://docs.python.org/3/library/os.html)
By completing this lesson, you'll gain a practical skill in file handling in Python, specifically tailored for working with Markdown files in a given directory.