File Handling
File Handling
File Handling
Let’s explore various Python data types and how data can be stored in different file
formats. Let’s understand the importance of file handling, which is crucial for
creating, reading, updating, and deleting files. Using Python's open() built-in function,
we can manipulate data in various file formats, such as .txt, .json, .xml, .csv, .tsv,
and .excel. Let's start by understanding file handling in Python, especially focusing
on the common .txt file format
Syntax:
The mode parameter specifies the operation: read (r), append (a), write (w), create (x),
text (t), and binary (b). Here's a detailed look at each mode:
● "r" - Read: This is the default mode. It opens a file for reading and returns an
error if the file does not exist. Useful for reading file contents without
modifying them.
● "a" - Append: Opens a file for appending at the end without truncating its
existing content. If the file doesn't exist, it's created. Ideal for adding data to
logs or data files.
● "w" - Write: Opens a file for writing, truncating the file first. If the file doesn't
exist, it's created. Use this mode for writing new data while removing old data.
● "x" - Create: Specifically for creating a new file. Returns an error if the file
already exists, ensuring no data is overwritten accidentally.
● "t" - Text: The default mode, indicating that operations are performed in text
mode. It interprets files as containing strings.
● "b" - Binary: For binary mode operations. It treats files as binary, which is
essential for non-text files like images and executables.
If you do not specify the mode, Python assumes you want to read the file, hence the
default mode is 'r' (or 'rt', which stands for "read text"). Here's an example of opening
a file named reading_file_example.txt located in a directory named files:
When working with file paths in Python, especially on Windows, you need to be
mindful of the backslash (\) character because it is used to escape characters that
otherwise have a special meaning, like newline (\n) or tab (\t). To correctly specify a
Windows file path in the Python open() function use double backslashes to avoid the
backslash being interpreted as an escape character:
Reading from Files
Once a file is opened for reading, there are several methods to retrieve its contents:
● read() Method: Reads the entire content of the file into a single string.
Optionally, you can pass an integer to read(number) to specify the number of
characters to read.
● readline() Method: It is used to read a single line from the file each time it is
called. If the end of the file (EOF) is reached, readline() returns an empty
string ('')
● readlines() Method: Reads all the lines in a file and returns them as a list of
strings.
Practical Examples
● Appending Log Entries: Use append mode to add new log entries to a log file,
preserving the existing entries.
● Generating Reports: Use write mode to create or overwrite a report file with
fresh data.
"x" - Create Mode
● Purpose: The "x" mode is used for creating a new file. If the file already exists,
the operation will fail, making it a safe way to ensure that new files are created
without overwriting existing files.
● Use Case: Ideal for scenarios where you want to ensure that a new file is
being created and not accidentally overwriting an existing file.
● Example:
In this example, text_file.txt is opened in text mode for writing. The mode "wt"
explicitly specifies writing in text mode, although just "w" would suffice since "t" is
the default.
"b" - Binary Mode
● Purpose: The "b" mode is used for binary files. This mode treats the file as a
binary blob, which is essential for non-text files like images, videos, executable
files, or even text files encoded in a specific encoding that you want to read or
write byte by byte.
● Use Case: Necessary for processing binary data, such as reading or writing
images, audio files, or any file where the data must not be treated as text.
● Example:
In this example, image.png is opened in binary read mode. The file's content is read
as bytes, and the example prints the first byte of the file.