Course Content
Introduction to Programming and Python
Overview of Python History and evolution Python’s features and benefits Set-Up Development Environment Installing Python and IDE (e.g., PyCharm, VS Code) Writing and running your first Python program Hands-On Activity Write a simple Python program to display “Hello, World!”
0/3
Structure Of A Python Program
A comprehensive overview of the structure of a Python program, covering essential concepts efficiently.
0/1
Basic Syntax and Control Statements
Basic Syntax Structure of a Python program Data types, variables, and operators
0/3
Object-Oriented Programming (OOP)
0/3
Python Programming For Beginners
About Lesson

Reading from and Writing to Files

  • Definition: File I/O (Input/Output) operations allow you to read from and write to files.
  • Opening a File: Use the open() function to open a file. The mode specifies whether you want to read ('r'), write ('w'), or append ('a') to the file. python
    file = open("example.txt", "r") # Open for reading file = open("example.txt", "w") # Open for writing file = open("example.txt", "a") # Open for appending
  • Reading from a File: Use methods like read()readline(), or readlines() to read the content. python
    file = open("example.txt", "r") content = file.read() print(content) file.close()
  • Writing to a File: Use the write() method to write content to a file. python
    file = open("example.txt", "w") file.write("Hello, World!") file.close()
  • Using with Statement: The with statement ensures that the file is properly closed after its suite finishes. python
    with open("example.txt", "r") as file: content = file.read() print(content)

Working with File Paths

  • Definition: File paths specify the location of a file in the file system.
  • Absolute vs. Relative Paths:
    • Absolute Path: Specifies the complete path from the root directory. python
      file = open("/home/user/example.txt", "r")
    • Relative Path: Specifies the path relative to the current working directory. python
      file = open("example.txt", "r")
  • Using os and pathlib Modules: These modules provide functions to work with file paths. python
    import os print(os.path.abspath("example.txt")) # Output: /home/user/example.txt from pathlib import Path print(Path("example.txt").resolve()) # Output: /home/user/example.txt

PAGE TOP