Introduction to Python Files (1)
Introduction to Python Files (1)
Python File handling is an essential concept in Python's programming framework. It enables you
to use your Python code directly to create, read, write, and manage files. The ability to
handle data storage, retrieval, and modification in a flexible manner facilitates the
management and processing of huge datasets.
A file is a named location used for storing data . Python has file-handling
functionality, enabling users to read, write, and perform various other file-handling operations on
files.
Although the idea of file handling has been extended to many other languages, its
implementation is typically difficult or time-consuming. However, this idea is simple to
understand, just like other Python concepts.
Python handles text and binary files differently, and this is significant. A text file is formed by
the characters that make up each line of code.
In Python Programming Language each line of text is terminated, delimited with a special
character known as EOL (End Of Line). In python the ‘EOL’ character is the new line
character (\n).
It's essential to understand the two main file formats in Python when working with files:
1. Binary Files:
Unlike text files, binary files contain data like pictures, films, or computer programs
Example:
2. Text files:
Typically ending in.txt, these files contain data in a readable format for humans to access.
Any text editor can be used to edit the plain text that they contain.
Text files can be handled in Python utilizing modes like a for appending, w for writing, and r
for reading.
Text files don’t have any specific encoding and it can be opened in normal text editor itself.
Example:
content = file.read()
print(content)
file.write("Hello, world!")
Appending Data to Files in Python
file.write("\nAppended text.")
binary_data = file.read()
Opening a file is the first step in doing any activity on it, whether writing or reading.
The open() function in Python is used for this, and it returns a file object that lets you work with
the file.
However, we must define the mode that represents the purpose of the opening file.
f = open(filename, mode)
r: Allows you to read an existing file. An error happens if the file is missing.
w: Allows writing to an open file. Data in the file will be removed if it already exists. If the file
doesn't exist, a new one is created.
a: Opens a file to add data at the end. It keeps the info that already exists.
r+: Allows you to read and write to a file. You can make changes to the file from the beginning
without deleting any already-existing content.
w+: Allows you to write and read data in a file. It erases any existing data. If the file doesn't
exist, it creates a new one.
a+: Allows you to read and append files. It adds data to the end without erasing existing content.
When you open a file in read mode (r), you are prepared to view its contents without making any
changes. This is how it works.
Use the open() function with the "r" mode to open the file.
Reading Content:
You can read the entire content or specific parts of the file using methods like read(), readline(),
or readlines()
There are three ways in which we can read the files in python.
1. read()
2. readline()
3. readlines()
1)READ():
READLINE() AND READLINES():
You can return one line by using the read line() method
By calling read line() two times, you can read the two first lines.
By using read lines() ,it will return every line in the file.
content = file.read()
print(content)
Using the with statement ensures the file is automatically closed after the operation is complete.
By looping through the lines of the file, you can read the whole file, line by line. It is fast and
efficient method.
The write() function is used to add text to a file. You can write a single line or multiple lines of
text in sequence.
Example
file.write("Welcome to Python\n")
file.write("789 101\n")
We can also integrate the written statement with the with() method.
file.write("Welcome to Python\n")
This function adds additional content to the end of an existing file without deleting the old data.
This allows you to preserve the original material while providing additional information.
Example
file.write("Python is versatile.\n")
file.close()
This code uses the open("Scholarhat.txt", "a") function to open the file in append mode, allowing
you to add new content to the end of the file without damaging existing data. The write()
function is then used to add two additional lines of text. Finally, the file is closed by calling the
file. close() to save the modifications.
After completing any file activity, use the close() function to close the file. This ensures that all
modifications are stored while clearing up system resources. If you do not close the file, you may
experience problems such as data not being stored properly or running out of file handles in your
software.
Example
The open() function in Python is used to open a file, and it supports different modes for different
types of operations.
This will:
Create the file if it doesn't exist.
Overwrite the file if it does.
This will:
// line.strip() removes any leading and trailing whitespace, including newline characters (\n),
making the output cleaner.
Or
Clears the file content first (like w), then allows read/write.
try:
with open("newfile.txt", "x") as file:
file.write("This file is created exclusively.")
except FileExistsError:
print("File already exists.")
Write binary:
Method Description
.read(size) Reads size bytes or full file
.readline() Reads one line
.readlines() Returns list of lines
.write(string) Writes a string
.writelines(list) Writes a list of strings
.seek(offset) Moves the cursor to a byte position
.tell() Returns current cursor position
.close() Closes the file manually
filename = "test.txt"
# Write Mode
with open(filename, "w") as f:
f.write("First line.\nSecond line.\n")
# Append Mode
with open(filename, "a") as f:
f.write("Third line.\n")