Course Content
Python MySQL
Python provides several libraries for working with MySQL databases. One popular library is mysql-connector-python, which allows you to connect to a MySQL database, execute queries, and fetch results.
Python MongoDB
Python SQLite
Python Questions
Python Programs
Mastering Python Programming: A Comprehensive Guide for Beginners
About Lesson

1. Reading a File:
You can read the contents of a file using the `open()` function and the `read()` method.

“`python
# Open the file in read mode
file = open(‘example.txt’, ‘r’)

# Read the entire contents of the file
content = file.read()

# Print the contents
print(content)

# Close the file
file.close()
“`

2. Writing to a File:
You can write to a file using the `open()` function with the `’w’` mode and the `write()` method.

“`python
# Open the file in write mode
file = open(‘example.txt’, ‘w’)

# Write content to the file
file.write(‘Hello, world!’)

# Close the file
file.close()
“`

3. Appending to a File:
If you want to add content to an existing file without overwriting its contents, you can use the `’a’` mode.

“`python
# Open the file in append mode
file = open(‘example.txt’, ‘a’)

# Append content to the file
file.write(‘ This is an appended line.’)

# Close the file
file.close()
“`

4. Reading Line by Line:
You can read a file line by line using a `for` loop or the `readline()` method.

“`python
# Open the file in read mode
file = open(‘example.txt’, ‘r’)

# Read and print each line
for line in file:
print(line)

# Close the file
file.close()
“`

5. Closing a File Automatically (with `with` statement):
The `with` statement automatically closes the file once you are done with it, even if an exception occurs.

“`python
# Open the file in read mode using the with statement
with open(‘example.txt’, ‘r’) as file:
# Read and print each line
for line in file:
print(line)
“`

6. Checking if a File Exists:
You can check if a file exists before opening it using the `os.path.exists()` function.

“`python
import os

# Check if the file exists
if os.path.exists(‘example.txt’):
print(‘File exists’)
else:
print(‘File does not exist’)
“`