Python Basics - File Handling
Working with files in Python
File handling is an essential part of programming, allowing you to read from and write to files. Python provides built-in functions for file handling, making it easy to work with files. This tutorial explores how to work with files in Python.
Key Points:
- File handling allows you to read from and write to files.
- The
open()
function is used to open a file. - Files can be opened in different modes, such as read ('r'), write ('w'), and append ('a').
- Always close the file after completing the operations using the
close()
method or a context manager (with
statement).
Opening a File
The open()
function is used to open a file. You need to specify the file name and the mode in which you want to open the file:
# Example of opening a file
file = open("example.txt", "r")
print(file.read())
file.close()
In this example, the file example.txt
is opened in read mode ('r'), and its contents are printed. The file is then closed using the close()
method.
Reading from a File
You can read from a file using various methods, such as read()
, readline()
, and readlines()
:
# Example of reading from a file
with open("example.txt", "r") as file:
content = file.read()
print(content)
# Reading one line at a time
with open("example.txt", "r") as file:
line = file.readline()
while line:
print(line, end='')
line = file.readline()
# Reading all lines into a list
with open("example.txt", "r") as file:
lines = file.readlines()
for line in lines:
print(line, end='')
In these examples, different methods are used to read the contents of the file. The with
statement is used to ensure that the file is properly closed after reading.
Writing to a File
You can write to a file using the write()
and writelines()
methods. Files can be opened in write mode ('w') or append mode ('a'):
# Example of writing to a file
with open("example.txt", "w") as file:
file.write("Hello, Python!\n")
file.write("This is a new line.\n")
# Appending to a file
with open("example.txt", "a") as file:
file.write("This line is appended.\n")
# Writing multiple lines
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("example.txt", "w") as file:
file.writelines(lines)
In these examples, different methods are used to write to the file. The with
statement is used to ensure that the file is properly closed after writing.
File Modes
Files can be opened in different modes, depending on the operation you want to perform:
'r'
: Read mode (default) - Opens the file for reading.'w'
: Write mode - Opens the file for writing (creates a new file or truncates an existing file).'a'
: Append mode - Opens the file for writing (creates a new file if it does not exist, appends to the existing file).'b'
: Binary mode - Opens the file in binary mode (used with other modes, e.g.,'rb'
or'wb'
).'t'
: Text mode (default) - Opens the file in text mode (used with other modes, e.g.,'rt'
or'wt'
).'+'
: Update mode - Opens the file for reading and writing (used with other modes, e.g.,'r+'
,'w+'
, or'a+'
).
Working with Binary Files
You can work with binary files by opening the file in binary mode ('b'). This is useful for reading and writing non-text files, such as images or executable files:
# Example of writing to a binary file
with open("example.bin", "wb") as file:
file.write(b'\x00\x01\x02\x03\x04')
# Example of reading from a binary file
with open("example.bin", "rb") as file:
data = file.read()
print(data)
In these examples, a binary file is written and read using binary mode.
File Operations
Python provides various methods for performing file operations, such as checking if a file exists, deleting a file, and renaming a file:
import os
# Check if a file exists
if os.path.exists("example.txt"):
print("File exists.")
else:
print("File does not exist.")
# Delete a file
os.remove("example.txt")
# Rename a file
os.rename("old_name.txt", "new_name.txt")
In these examples, the os
module is used to perform various file operations.
Summary
In this tutorial, you learned about file handling in Python. You explored how to open, read from, and write to files using built-in functions and methods. You also learned about different file modes, working with binary files, and performing various file operations. Understanding file handling is essential for working with data stored in files and for building applications that require file operations.