File I/O and Modules in Python
Python tutorial · PySpark.in
Introduction to File I/O
File I/O (Input/Output) in Python means reading from and writing to files stored on your system.
It allows you to:
- Save program data permanently
- Read data from external sources (like text files, logs, CSVs, etc.)
Opening and Closing Files
Python provides the built-in function open() to work with files.
Syntax:
Mode | Description |
|---|---|
'r' | Read (default). File must exist. |
'w' | Write. Creates a new file or overwrites an existing one. |
'a' | Append. Adds data at the end of the file. |
'r+' | Read and write. File must exist. |
'w+' | Write and read. Creates new file or overwrites. |
'a+' | Append and read. Creates file if not exist. |
Reading from a File
Example:
Note: Always close a file after using it to free up system resources.
Other Read Methods
Method | Description |
|---|---|
file.read(size) | Reads specified number of bytes. |
file.readline() | Reads one line at a time. |
file.readlines() | Reads all lines and returns a list. |
Writing to a File
Example (Write Mode):
If the file exists, it will overwrite it.
Example (Append Mode):
This adds content at the end of the file without deleting previous data.
Reading and Writing Together
More Python tutorials
- What is Python and Why is it used for Data Science and Data Engineering?
- How Does Python Work in the Backend? Internal Working of Python
- Top 30 Python Interview Questions for Data Science
- 3-Month Python Roadmap to Excel in Data Science and Machine Learning
- Python Data Types Explained – A Beginner’s Guide
- test
All tutorials · Try the free PySpark compiler · Practice challenges