File handling in Python allows us to create, open, read, write, update, and delete files. File handling is useful when data needs to be stored permanently instead of keeping it only in program memory.
open() function for working
with files.
File handling means performing operations on files using a programming language.
Common file operations include:
Variables store data temporarily while a program is running. Files can store data so that it can remain available after the program finishes.
For example:
name = "Amit"
The value is stored in memory while the program runs. A file can be used when the data needs to be saved for later use.
The open() function is used to open a file.
Basic syntax:
open("filename", "mode")
Example:
file = open("data.txt", "r")
Here, data.txt is the file name and r means
read mode.
| Mode | Meaning |
|---|---|
r |
Read an existing file. |
w |
Write to a file. Creates it if needed and replaces existing content. |
a |
Append data to the end of a file. |
x |
Create a new file and fail if it already exists. |
b |
Binary mode. |
t |
Text mode. |
+ |
Update mode for reading and writing. |
The read() method reads the contents of a file.
file = open("data.txt", "r")
content = file.read()
print(content)
file.close()
The close() method closes the file after the operation is complete.
The w mode allows us to write data to a file.
file = open("data.txt", "w")
file.write("Hello Python")
file.close()
If the file does not exist, Python creates it. If it already exists, its previous contents are replaced.
The a mode adds new content to the end of an existing file.
file = open("data.txt", "a")
file.write("\nWelcome to Python")
file.close()
Unlike w mode, append mode does not replace the existing
contents.
The x mode is used to create a new file.
file = open("newfile.txt", "x")
file.write("New file created")
file.close()
If the file already exists, opening it with x mode raises
a FileExistsError.
The close() method closes an opened file.
file = open("data.txt", "r")
print(file.read())
file.close()
Closing files helps release system resources after the file operation is finished.
The closed attribute tells whether a file object has been closed.
file = open("data.txt", "r")
print(file.closed)
file.close()
print(file.closed)
The with statement is the recommended way to work with files
in many situations.
with open("data.txt", "r") as file:
content = file.read()
print(content)
When the with block finishes, Python automatically closes
the file.
with open("data.txt", "w") as file:
file.write("Python File Handling")
The file is automatically closed after the with block.
with open("data.txt", "r") as file:
data = file.read()
print(data)
The read() method returns the file contents as a string
when working with a text file.
You can pass a number to read() to read a specific number
of characters.
with open("data.txt", "r") as file:
data = file.read(5)
print(data)
This reads up to the first five characters from the current file position.
The readline() method reads one line at a time.
with open("data.txt", "r") as file:
line = file.readline()
print(line)
Calling readline() again reads the next line.
The readlines() method reads the lines of a text file and
returns them as a list.
with open("data.txt", "r") as file:
lines = file.readlines()
print(lines)
A file object can be iterated over directly to process one line at a time.
with open("data.txt", "r") as file:
for line in file:
print(line.strip())
This approach is useful when processing large text files because it does not require loading the entire file into a list first.
The write() method writes a string to a file.
with open("data.txt", "w") as file:
file.write("Hello\n")
file.write("Welcome to Python\n")
file.write("File Handling")
The \n character starts a new line.
The writelines() method writes multiple strings to a file.
It does not automatically add newline characters.
lines = [
"Python\n",
"Java\n",
"JavaScript\n"
]
with open("languages.txt", "w") as file:
file.writelines(lines)
Python keeps track of the current position in an opened file.
The tell() method returns the current position.
with open("data.txt", "r") as file:
print(file.tell())
The position is measured in bytes for binary streams and generally in text-stream units for text files.
The seek() method changes the current file position.
with open("data.txt", "r") as file:
file.seek(0)
data = file.read()
print(data)
Using seek(0) moves the file position back to the beginning
for a typical text file.
When working with text files, it is often a good practice to specify the encoding explicitly.
with open(
"data.txt",
"r",
encoding="utf-8"
) as file:
data = file.read()
print(data)
UTF-8 is a widely used text encoding and supports many languages.
Trying to open a missing file in read mode can raise
FileNotFoundError.
try:
with open("missing.txt", "r") as file:
data = file.read()
except FileNotFoundError:
print("File does not exist")
Python can work with both text and binary files.
| Text File | Binary File |
|---|---|
| Stores text data. | Stores binary data. |
| Examples: TXT, CSV | Examples: images, PDFs, executable files |
| Usually opened using text mode. | Use b mode. |
Example:
with open("image.jpg", "rb") as file:
data = file.read()
Python's os module can be used to delete a file.
import os
if os.path.exists("data.txt"):
os.remove("data.txt")
print("File deleted")
else:
print("File does not exist")
The os.path.exists() function checks whether a path exists.
import os
if os.path.exists("data.txt"):
print("File exists")
else:
print("File does not exist")
The following example creates a file, writes data to it, and then reads the data.
with open("student.txt", "w", encoding="utf-8") as file:
file.write("Name: Rahul\n")
file.write("Course: Python\n")
file.write("Age: 21\n")
with open("student.txt", "r", encoding="utf-8") as file:
data = file.read()
print(data)
with open() pattern for normal file operations.open() function is used to work with files.r is used for reading.w is used for writing and can replace existing content.a is used for appending.x creates a new file and fails if it already exists.read(), readline(), and readlines() are used for reading.write() and writelines() are used for writing.with open() automatically closes the file.seek() changes the file position.tell() returns the current file position.os module can be used for filesystem operations such as checking and deleting files.Question: Which file mode is used to append data to the end of a file?