File Handling allows you to create, read, write, and manage files in Python. Python provides the built-in open() function to work with files.
Opening a File
The open() function is used to open a file.
Syntax
open(file_name, mode)
Example
file = open("sample.txt", "r")
File Modes
| Mode | Description |
|---|---|
r | Read file |
w | Write file (overwrites existing content) |
a | Append data to file |
x | Create a new file |
r+ | Read and write |
b | Binary mode |
t | Text mode (default) |
Reading a File
Example
file = open("sample.txt", "r")
print(file.read())
file.close()
Output:
Hello Python
Reading a Specific Number of Characters
Example
file = open("sample.txt", "r")
print(file.read(5))
file.close()
Output:
Hello
Reading a Single Line
Example
file = open("sample.txt", "r")
print(file.readline())
file.close()
Output:
Hello Python
Reading All Lines
Example
file = open("sample.txt", "r")
print(file.readlines())
file.close()
Output:
['Hello Python\n', 'Welcome']
Loop Through a File
Example
file = open("sample.txt", "r")
for line in file:
print(line)
file.close()
Writing to a File
The w mode creates a file if it does not exist and overwrites existing content.
Example
file = open("sample.txt", "w")
file.write("Hello Python")
file.close()
Appending to a File
The a mode adds content to the end of a file.
Example
file = open("sample.txt", "a")
file.write("\nWelcome")
file.close()
Using with Statement
The with statement automatically closes the file.
Example
with open("sample.txt", "r") as file:
print(file.read())
Output:
Hello Python
Welcome
Check if File Exists
Example
import os
if os.path.exists("sample.txt"):
print("File exists")
else:
print("File not found")
Output:
File exists
Summary
open()is used to work with files.- File modes determine how a file is accessed.
read(),readline(), andreadlines()are used to read file content.write()writes data to a file.append()mode adds data without removing existing content.close()closes a file after use.- The
withstatement automatically handles file closing. - File existence can be checked using the
osmodule.