Python with open, os Module, Modules and Keywords Explained

The with open statement in Python opens a file, hands you a file object to read or write, and automatically closes the file when the indented block ends — even if an exception occurs. It uses Python’s context manager protocol, so you never need to call file.close() manually. This single pattern prevents resource-leak bugs in every real Python project.

  • with open() closes the file automatically, even on exceptions.
  • The os module gives you cross-platform access to file paths, environment variables and directory operations.
  • A module is a single .py file; a package is a folder of modules with an __init__.py file.
  • Python 3.12 has 35 reserved keywords, according to the official Python 3 documentation.
  • The global keyword lets a function read and modify a variable that lives in the module’s top-level scope.

Reading and Writing Files with ‘with open’

Before with open python became the standard, beginners would call open(), do some work, and then forget to call close(). On a busy server handling thousands of requests, unclosed file handles can exhaust the operating system’s file-descriptor limit fast. The with statement, introduced formally via PEP 343, solves this at the language level.

How the Syntax Breaks Down

Part What it does Example value
open(file, mode) Opens the file and returns a file object open("marks.txt", "r")
as f Binds the file object to a local name f is now your handle
Indented block All read/write operations go here data = f.read()
Block exit Python calls f.__exit__() automatically File is closed, no matter what

Common File Modes in Python open()

  • “r” – read only (default); raises FileNotFoundError if the file is missing.
  • “w” – write; creates the file or overwrites it if it exists.
  • “a” – append; adds to the end without erasing existing content.
  • “rb” / “wb” – binary modes, used for images, PDFs or any non-text data.

What Is the Difference Between with open and open in Python?

Using open() alone returns a file object but places the responsibility of closing it entirely on you. If your code raises an exception before reaching file.close(), the file stays open. The with open python pattern wraps the same open() call inside a context manager that guarantees __exit__ is called on block exit, whether the block succeeds or fails. For production code, always prefer with open over bare open().

A Practical Example: Storing Student Marks

Imagine you’re building a small attendance tracker for a BCA or BSc Computer Science class at an Indian university. You’d write each student’s name and marks to a file like this: with open("marks.txt", "a") as f: f.write("Priya,89\n"). When the block ends, Python closes the file cleanly. Reading it back is just as simple: with open("marks.txt", "r") as f: print(f.read()).

One real-world tip: always specify the encoding explicitly, especially if you’re writing data that includes Hindi or other non-ASCII characters. Use open("marks.txt", "r", encoding="utf-8") to avoid UnicodeDecodeError surprises on Windows machines where the default encoding is often cp1252. This is a common issue for developers working across Windows laptops and Linux servers, a setup that is extremely common in Indian IT services firms like TCS, Infosys and Wipro.

If you’re just getting started with Python and haven’t set up your environment yet, check out our guide on how to write and run a Python program before going further.

How to Read a File Line by Line in Python

For large files, reading the entire content into memory with f.read() is inefficient. Instead, iterate directly over the file object inside your with open python block: with open("marks.txt", "r", encoding="utf-8") as f: for line in f: print(line.strip()). Python reads one line at a time, keeping memory usage flat regardless of file size. This technique is essential for processing large log files or datasets in data engineering pipelines.

The os Module in Python

The os module is part of Python’s standard library and gives your script a consistent interface to the underlying operating system, whether that’s Windows, Linux or macOS. You import it with a single line: import os. No installation needed.

Key os Module Functions and What They Do

  • os.getcwd() – returns the current working directory as a string.
  • os.listdir(path) – lists all files and folders inside a directory.
  • os.mkdir(name) – creates a new directory.
  • os.path.join() – builds file paths correctly for any OS, so you don’t hardcode slashes.
  • os.environ.get(“HOME”) – reads environment variables, which is critical for keeping API keys out of your source code.
  • os.rename(src, dst) – renames or moves a file.
  • os.remove(path) – deletes a file.

os vs pathlib: Which One Should You Use?

Python 3.4 introduced the pathlib module as an object-oriented alternative to os.path. For most new code, pathlib.Path is cleaner and more readable. That said, os is still everywhere in production codebases, so you need to understand both. Many automation scripts you’ll encounter in DevOps and security tooling rely heavily on os. In Indian campus placement drives at IITs, NITs and private engineering colleges, questions on the python os module functions appear regularly in technical screening rounds.

The python os module becomes especially powerful when you combine it with shell operations. If you also work in Linux, our guides on shell scripting in Linux and basic Linux commands show how Python scripts and shell scripts often complement each other in automation pipelines.

According to the Stack Overflow Developer Survey 2024, Python is the most-used language among professional developers for the third year running, with 51% of respondents using it regularly. A big part of that dominance comes from exactly these standard-library tools: file handling, OS interaction and module imports that just work out of the box.

According to the JetBrains State of Developer Ecosystem 2023 report, 58% of Python developers use Python primarily for scripting and automation tasks, which includes file handling with with open python and OS operations via the os module. This makes file I/O one of the most practically important Python skills to master early.

Modules, Packages and Keywords in Python

What Is a Module?

A module is any .py file you can import. When you write import math, Python loads math.py from the standard library and makes all its functions available under the math namespace. You can write your own module by saving a file as, say, utils.py and importing it with import utils in another file in the same directory.

What Is a Package?

A package is a folder that contains multiple modules and an __init__.py file. That __init__.py can be empty; its presence is what tells Python to treat the folder as a package rather than a plain directory. So if you have a folder called school/ with students.py and marks.py inside it, and an empty __init__.py, you can do from school import students in your main script.

Understanding modules and packages in python properly is the foundation for working with any third-party library. When you run pip install requests, pip downloads a package and drops it into your environment’s site-packages folder. That’s it. The import system handles the rest.

Python Keywords List: All 35 Reserved Words in Python 3.12

A keyword in Python is a reserved word that the interpreter treats as part of the language syntax. You can’t use them as variable names. Python 3.12 has exactly 35 keywords, as listed in the official Python 3.12 documentation.

Category Keywords
Control flow if, elif, else, for, while, break, continue, pass, return
Boolean and comparison True, False, None, and, or, not, is, in
Functions and classes def, class, lambda, yield, async, await
Scope and variables global, nonlocal, del
Exceptions and context try, except, finally, raise, with, as, assert
Imports import, from

You can always check the current list inside Python by running import keyword; print(keyword.kwlist). That command is handy during interviews, where questions about the keywords of python come up regularly at companies like TCS, Infosys and Wipro. Under India’s NEP 2020 curriculum framework, Python keywords and file handling are now part of the standard BTech and BSc Computer Science syllabus across AICTE-affiliated colleges.

If you’re studying for a BTech or BSc Computer Science programme and want to understand where Python fits across your full curriculum, that linked guide gives a useful overview.

Comments and global Variables in Python

Writing Comments in Python

A comment in python starts with a # symbol. Everything after # on that line is ignored by the interpreter. Comments are for humans, not the machine. They explain intent, warn about edge cases, or mark sections of code that need revisiting.

Multi-line comments don’t have a dedicated syntax in Python. The convention is to use consecutive # lines, or to use a triple-quoted string ("""...""") that isn’t assigned to anything. Triple-quoted strings are also how you write docstrings, which tools like Sphinx and IDEs use to generate documentation automatically.

One practical tip: don’t comment what the code does if the code is already readable. Comment why you made a specific choice. A line like # using append mode to avoid overwriting existing logs is far more useful than # opens file.

The global Keyword in Python

By default, a variable you create inside a function exists only inside that function. The python global keyword changes that. When you write global count inside a function, Python knows you want to read and modify the count variable that lives at the module level, not create a new local one.

Here’s where beginners get burned: if you forget global and try to increment a module-level counter inside a function, Python raises an UnboundLocalError. It sees the assignment inside the function and assumes count is local, but it hasn’t been defined locally yet. Adding global count at the top of the function fixes it immediately.

That said, over-using global is a code smell. If you find yourself declaring five global variables in a single function, that’s a signal to refactor using a class or to pass values as function arguments. The TIOBE Index for April 2025 still places Python at rank 1, and one reason experienced Python developers keep it there is disciplined use of scope.

For a broader view of how with open python patterns, OS operations and modules fit into automation, data work and web projects, our guide on Python for automation, web scraping and APIs is a solid next read. And if you’re still choosing which tools to learn alongside Python, the software development tools to learn first guide covers the full stack of essentials.

Frequently Asked Questions

What does with open do in Python?

with open() opens a file and automatically closes it when the indented block finishes, even if an exception is raised inside the block. It uses Python’s context manager protocol, defined in PEP 343, calling __enter__ on entry and __exit__ on exit. This prevents file-descriptor leaks and is the recommended way to handle files in all modern Python code.

What is the difference between with open and open in Python?

Using bare open() returns a file object but requires you to call file.close() manually. If an exception occurs before that line, the file stays open and leaks a file descriptor. The with open python pattern guarantees the file is closed on block exit regardless of whether an exception occurred, making it safer and cleaner for all file operations.

What is the os module in Python?

The os module is a built-in Python library that provides a portable interface to operating system functionality. It lets you list directories, create folders, read environment variables, rename files and build cross-platform file paths using os.path.join(). You access it with import os and no additional installation is required.

What is the difference between a module and a package in Python?

A module is a single .py file containing Python code you can import. A package is a directory of modules that includes an __init__.py file, which signals to Python that the folder should be treated as an importable unit. Most third-party libraries you install with pip are packages made up of many modules.

How many keywords does Python have?

Python 3.12 has 35 reserved keywords, as documented on python.org. These include words like if, for, def, class, global, with, import and True. You can view the current list at any time by running import keyword; print(keyword.kwlist) in a Python shell.

What does the global keyword do in Python?

The global keyword tells Python that a variable inside a function refers to the module-level variable of the same name, rather than creating a new local one. Without it, assigning to a variable inside a function creates a local copy. Use it sparingly; passing values through function arguments or using a class is usually cleaner design.

You now have a solid grip on file handling with with open python, OS operations, modules, keywords and scope in Python. These aren’t abstract concepts; they show up in every real script, from a log parser to a web scraper to a security tool. Here are three things to do this week:

  1. Write a small script that uses with open to read a CSV file, then uses os.path.exists() to check the file exists before opening it.
  2. Create your own module by saving a few utility functions in a helpers.py file and importing them into a separate script.
  3. Explore how these foundations connect to real-world security work. Strong Python skills are the bedrock of ethical hacking, secure coding and AI development. Browse the 3.0 University online certification courses or go straight to the CEH v13 AI online course to see how Python fits into a professional cybersecurity career.

Last updated: May 2025. Reviewed by the 3University editorial team.

We create, review, and maintain educational content covering Cybersecurity, Ethical Hacking, Artificial Intelligence, Blockchain, Web3, and emerging technologies.

Read More Articles