In Python, a file is a way to store data persistently on disk. Files are used for various purposes such as saving program output, reading input data, and managing large datasets. Python provides built-in functions and methods to handle files efficiently, allowing you to perform operations like reading from and writing to files.
Basic File Operations
Opening a File
To work with a file, you first need to open it using the open()
function. This function returns a file object, which you can use to interact with the file.
'example.txt'
: The name of the file you want to open.'r'
: Mode in which to open the file. Common modes include:
'r'
: Read mode (default).'w'
: Write mode (creates or truncates a file).'a'
: Append mode (adds to the end of a file).'b'
: Binary mode (e.g., 'rb'
for reading binary files).Reading from a File
Once a file is opened, you can read its content using methods like read()
, readline()
, or readlines()
.
read()
: Reads the whole file content.readline()
: Reads a single line.readlines()
: Reads all lines into a list.Writing to a File
To write data to a file, open it in write ('w'
) or append ('a'
) mode and use the write()
method.
write()
: Writes a string to the file.Appending to a File
To add data to the end of an existing file without truncating it, use append mode.
Closing a File
Always close a file after finishing operations to ensure that resources are freed and changes are saved.
close()
: Closes the file object.Using the **with**
Statement
The with
statement simplifies file handling by automatically closing the file when done, even if an error occurs.
Practical Examples
Reading and Writing Text Files:
Processing CSV Files:
Practical Use Cases
Understanding how to work with files in Python is crucial for managing and manipulating data efficiently. By learning to open, read, write, and close files—whether through direct methods or using the with
statement—you can handle a wide range of file-based tasks in your Python programs. Effective file handling enables you to save data persistently, process large datasets, and manage configurations with ease.