- Python Basics
- Python - Home
- Python - Overview
- Python - History
- Python - Features
- Python vs C++
- Python - Hello World Program
- Python - Application Areas
- Python - Interpreter
- Python - Environment Setup
- Python - Virtual Environment
- Python - Basic Syntax
- Python - Variables
- Python - Data Types
- Python - Type Casting
- Python - Unicode System
- Python - Literals
- Python - Operators
- Python - Arithmetic Operators
- Python - Comparison Operators
- Python - Assignment Operators
- Python - Logical Operators
- Python - Bitwise Operators
- Python - Membership Operators
- Python - Identity Operators
- Python - Operator Precedence
- Python - Comments
- Python - User Input
- Python - Numbers
- Python - Booleans
- Python Control Statements
- Python - Control Flow
- Python - Decision Making
- Python - If Statement
- Python - If else
- Python - Nested If
- Python - Match-Case Statement
- Python - Loops
- Python - for Loops
- Python - for-else Loops
- Python - While Loops
- Python - break Statement
- Python - continue Statement
- Python - pass Statement
- Python - Nested Loops
- Python Functions & Modules
- Python - Functions
- Python - Default Arguments
- Python - Keyword Arguments
- Python - Keyword-Only Arguments
- Python - Positional Arguments
- Python - Positional-Only Arguments
- Python - Arbitrary Arguments
- Python - Variables Scope
- Python - Function Annotations
- Python - Modules
- Python - Built in Functions
- Python Strings
- Python - Strings
- Python - Slicing Strings
- Python - Modify Strings
- Python - String Concatenation
- Python - String Formatting
- Python - Escape Characters
- Python - String Methods
- Python - String Exercises
- Python Lists
- Python - Lists
- Python - Access List Items
- Python - Change List Items
- Python - Add List Items
- Python - Remove List Items
- Python - Loop Lists
- Python - List Comprehension
- Python - Sort Lists
- Python - Copy Lists
- Python - Join Lists
- Python - List Methods
- Python - List Exercises
- Python Tuples
- Python - Tuples
- Python - Access Tuple Items
- Python - Update Tuples
- Python - Unpack Tuples
- Python - Loop Tuples
- Python - Join Tuples
- Python - Tuple Methods
- Python - Tuple Exercises
- Python Sets
- Python - Sets
- Python - Access Set Items
- Python - Add Set Items
- Python - Remove Set Items
- Python - Loop Sets
- Python - Join Sets
- Python - Copy Sets
- Python - Set Operators
- Python - Set Methods
- Python - Set Exercises
- Python Dictionaries
- Python - Dictionaries
- Python - Access Dictionary Items
- Python - Change Dictionary Items
- Python - Add Dictionary Items
- Python - Remove Dictionary Items
- Python - Dictionary View Objects
- Python - Loop Dictionaries
- Python - Copy Dictionaries
- Python - Nested Dictionaries
- Python - Dictionary Methods
- Python - Dictionary Exercises
- Python Arrays
- Python - Arrays
- Python - Access Array Items
- Python - Add Array Items
- Python - Remove Array Items
- Python - Loop Arrays
- Python - Copy Arrays
- Python - Reverse Arrays
- Python - Sort Arrays
- Python - Join Arrays
- Python - Array Methods
- Python - Array Exercises
- Python File Handling
- Python - File Handling
- Python - Write to File
- Python - Read Files
- Python - Renaming and Deleting Files
- Python - Directories
- Python - File Methods
- Python - OS File/Directory Methods
- Python - OS Path Methods
- Object Oriented Programming
- Python - OOPs Concepts
- Python - Classes & Objects
- Python - Class Attributes
- Python - Class Methods
- Python - Static Methods
- Python - Constructors
- Python - Access Modifiers
- Python - Inheritance
- Python - Polymorphism
- Python - Method Overriding
- Python - Method Overloading
- Python - Dynamic Binding
- Python - Dynamic Typing
- Python - Abstraction
- Python - Encapsulation
- Python - Interfaces
- Python - Packages
- Python - Inner Classes
- Python - Anonymous Class and Objects
- Python - Singleton Class
- Python - Wrapper Classes
- Python - Enums
- Python - Reflection
- Python Errors & Exceptions
- Python - Syntax Errors
- Python - Exceptions
- Python - try-except Block
- Python - try-finally Block
- Python - Raising Exceptions
- Python - Exception Chaining
- Python - Nested try Block
- Python - User-defined Exception
- Python - Logging
- Python - Assertions
- Python - Built-in Exceptions
- Python Multithreading
- Python - Multithreading
- Python - Thread Life Cycle
- Python - Creating a Thread
- Python - Starting a Thread
- Python - Joining Threads
- Python - Naming Thread
- Python - Thread Scheduling
- Python - Thread Pools
- Python - Main Thread
- Python - Thread Priority
- Python - Daemon Threads
- Python - Synchronizing Threads
- Python Synchronization
- Python - Inter-thread Communication
- Python - Thread Deadlock
- Python - Interrupting a Thread
- Python Networking
- Python - Networking
- Python - Socket Programming
- Python - URL Processing
- Python - Generics
- Python Libraries
- NumPy Tutorial
- Pandas Tutorial
- SciPy Tutorial
- Matplotlib Tutorial
- Django Tutorial
- OpenCV Tutorial
- Python Miscellenous
- Python - Date & Time
- Python - Maths
- Python - Iterators
- Python - Generators
- Python - Closures
- Python - Decorators
- Python - Recursion
- Python - Reg Expressions
- Python - PIP
- Python - Database Access
- Python - Weak References
- Python - Serialization
- Python - Templating
- Python - Output Formatting
- Python - Performance Measurement
- Python - Data Compression
- Python - CGI Programming
- Python - XML Processing
- Python - GUI Programming
- Python - Command-Line Arguments
- Python - Docstrings
- Python - JSON
- Python - Sending Email
- Python - Further Extensions
- Python - Tools/Utilities
- Python - GUIs
- Python Useful Resources
- Python Compiler
- NumPy Compiler
- Matplotlib Compiler
- SciPy Compiler
- Python - Questions & Answers
- Python - Online Quiz
- Python - Programming Examples
- Python - Quick Guide
- Python - Useful Resources
- Python - Discussion
Python - File Handling
File Handling in Python
File handling in Python involves interacting with files on your computer to read data from them or write data to them. Python provides several built-in functions and methods for creating, opening, reading, writing, and closing files. This tutorial covers the basics of file handling in Python with examples.
Opening a File in Python
To perform any file operation, the first step is to open the file. Python's built-in open() function is used to open files in various modes, such as reading, writing, and appending. The syntax for opening a file in Python is −
file = open("filename", "mode")
Where, filename is the name of the file to open and mode is the mode in which the file is opened (e.g., 'r' for reading, 'w' for writing, 'a' for appending).
File Opening Modes
Following are the file opening modes −
Sr.No. | Modes & Description |
---|---|
1 | r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode. |
2 | rb Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode. |
3 | r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file. |
4 | rb+ Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file. |
5 | w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. |
6 | b Opens the file in binary mode |
7 | t Opens the file in text mode (default) |
8 | + open file for updating (reading and writing) |
9 | wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. |
10 | w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. |
11 | wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. |
12 | a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. |
13 | ab Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. |
14 | a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. |
15 | ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. |
16 | x open for exclusive creation, failing if the file already exists |
Once a file is opened and you have one file object, you can get various information related to that file.
Example 1
In the following example, we are opening a file in different modes −
# Opening a file in read mode file = open("example.txt", "r") # Opening a file in write mode file = open("example.txt", "w") # Opening a file in append mode file = open("example.txt", "a") # Opening a file in binary read mode file = open("example.txt", "rb")
Example 2
In here, we are opening a file named "foo.txt" in binary write mode ("wb"), printing its name, whether it's closed, and its opening mode, and then closing the file −
# Open a file fo = open("foo.txt", "wb") print ("Name of the file: ", fo.name) print ("Closed or not: ", fo.closed) print ("Opening mode: ", fo.mode) fo.close()
It will produce the following output −
Name of the file: foo.txt Closed or not: False Opening mode: wb
Reading a File in Python
Reading a file in Python involves opening the file in a mode that allows for reading, and then using various methods to extract the data from the file. Python provides several methods to read data from a file −
read() − Reads the entire file.
readline() − Reads one line at a time.
readlines − Reads all lines into a list.
To read a file, you need to open it in read mode. The default mode for the open() function is read mode ('r'), but it's good practice to specify it explicitly.
Example: Using read() method
In the following example, we are using the read() method to read the whole file into a single string −
with open("example.txt", "r") as file: content = file.read() print(content)
Following is the output obtained −
Hello!!! Welcome to TutorialsPoint!!!
Example: Using readline() method
In here, we are using the readline() method to read one line at a time, making it memory efficient for reading large files line by line −
with open("example.txt", "r") as file: line = file.readline() while line: print(line, end='') line = file.readline()
Output of the above code is as shown below −
Hello!!! Welcome to TutorialsPoint!!!
Example: Using readlines() method
Now, we are using the readlines() method to read the entire file and splits it into a list where each element is a line −
with open("example.txt", "r") as file: lines = file.readlines() for line in lines: print(line, end='')
We get the output as follows −
Hello!!! Welcome to TutorialsPoint!!!
Writing to a File in Python
Writing to a file in Python involves opening the file in a mode that allows writing, and then using various methods to add content to the file.
To write data to a file, use the write() or writelines() methods. When opening a file in write mode ('w'), the file's existing content is erased.
Example: Using the write() method
In this example, we are using the write() method to write the string passed to it to the file. If the file is opened in 'w' mode, it will overwrite any existing content. If the file is opened in 'a' mode, it will append the string to the end of the file −
with open("foo.txt", "w") as file: file.write("Hello, World!") print ("Content added Successfully!!")
Output of the above code is as follows −
Content added Successfully!!
Example: Using the writelines() method
In here, we are using the writelines() method to take a list of strings and writes each string to the file. It is useful for writing multiple lines at once −
lines = ["First line\n", "Second line\n", "Third line\n"] with open("example.txt", "w") as file: file.writelines(lines) print ("Content added Successfully!!")
The result obtained is as follows −
Content added Successfully!!
Closing a File in Python
We can close a file in Python using the close() method. Closing a file is an essential step in file handling to ensure that all resources used by the file are properly released. It is important to close files after operations are completed to prevent data loss and free up system resources.
Example
In this example, we open the file for writing, write data to the file, and then close the file using the close() method −
file = open("example.txt", "w") file.write("This is an example.") file.close() print ("File closed successfully!!")
The output produced is as shown below −
File closed successfully!!
Using "with" Statement for Automatic File Closing
The with statement is a best practice in Python for file operations because it ensures that the file is automatically closed when the block of code is exited, even if an exception occurs.
Example
In this example, the file is automatically closed at the end of the with block, so there is no need to call close() method explicitly −
with open("example.txt", "w") as file: file.write("This is an example using the with statement.") print ("File closed successfully!!")
Following is the output of the above code −
File closed successfully!!
Handling Exceptions When Closing a File
When performing file operations, it is important to handle potential exceptions to ensure your program can manage errors gracefully.
In Python, we use a try-finally block to handle exceptions when closing a file. The "finally" block ensures that the file is closed regardless of whether an error occurs in the try block −
try: file = open("example.txt", "w") file.write("This is an example with exception handling.") finally: file.close() print ("File closed successfully!!")
After executing the above code, we get the following output −
File closed successfully!!