0% found this document useful (0 votes)
2 views15 pages

Introduction to Python Files (1)

The document provides a comprehensive overview of file handling in Python, detailing how to create, read, write, and manage both text and binary files. It explains various file modes and operations, including examples of syntax and usage for each mode. Additionally, it emphasizes the importance of closing files to ensure data integrity and resource management.

Uploaded by

ugowthami04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views15 pages

Introduction to Python Files (1)

The document provides a comprehensive overview of file handling in Python, detailing how to create, read, write, and manage both text and binary files. It explains various file modes and operations, including examples of syntax and usage for each mode. Additionally, it emphasizes the importance of closing files to ensure data integrity and resource management.

Uploaded by

ugowthami04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Python Files

Introduction to File Handling in Python

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.

What is File Handling in Python?

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).

Types of Files in Python

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

that are not readable by humans.

.bin or .dat are typical extensions for them.


Python handles similar to text files, binary files with the addition of a b suffix, such as rb for
reading binary files and wb for writing them. Most of the files that we see in our computer
system are called binary files.

Example:

1. Document files: .pdf, .doc, .xls etc.

2. Image files: .png, .jpg, .gif, .bmp etc.

3. Video files: .mp4, .3gp, .mkv, .avi etc.

4. Audio files: .mp3, .wav, .mka, .aac etc.

5. Database files: .mdb, .accde, .frm, .sqlite etc.

6. Archive files: .zip, .rar, .iso, .7z etc.

7. Executable files: .exe, .dll, .class etc.

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:

1. Web standards: html, XML, CSS, JSON etc.

2. Source code: c, app, js, py, java etc.

3. Documents: txt, tex, RTF etc.

4. Tabular data: csv, tsv etc.

5.Configuration: ini, cfg, reg etc.


Syntax of Python Basic File Handling

file_object = open(file_name, mode)

# Perform file operations

fo.read() # To read the content

fo.write(data) # To write data

fo.close() # To close the file


Python File Operations with Examples

Reading from a File in Python

with open("example.txt", "r") as file:

content = file.read()

print(content)

No need to explicitly close the file when using with.

Writing to Files in Python

with open("example.txt", "w") as file:

file.write("Hello, world!")
Appending Data to Files in Python

with open("example.txt", "a") as file:

file.write("\nAppended text.")

Working with Binary Files in Python

with open("image.jpg", "rb") as file:

binary_data = file.read()

How to Perform File Operations in Python?

Python File Operations

Consider the following “Scholarhat.txt” file as an example.

1) Opening Files in Python

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)

Wherever the mentioned mode is offered:

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.

2) Working in Read mode

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.

1. Opening the File:

Use the open() function with the "r" mode to open the file.

file = open("Scholarhat.txt", "r")

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.

read(): Reads the entire file as a single string.


content = file.read()
print(content)
readline(): Reads one line at a time.
line = file.readline()
print(line)
readlines(): Reads all lines into a list, where each element is a line.
lines = file.readlines()
print(lines)
Closing the File(): Always close the file after you're done to free up resources.
file.close()
Example
A simple example that reads and prints the content of "Scholarhat.txt":
with open("Scholarhat.txt", "r") as file:

content = file.read()

print(content)

Using the with statement ensures the file is automatically closed after the operation is complete.

LOOP OVER A FILE OBJECT:

By looping through the lines of the file, you can read the whole file, line by line. It is fast and
efficient method.

3) Creating a File using the write() Function

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("Learn with ScholarHat\n")

file.write("789 101\n")

Example using "with()" method

We can also integrate the written statement with the with() method.

with open("Scholarhat.txt", "w") as file:

file.write("Welcome to Python\n")

file.write("Learn with ScholarHat\n")


file.write("789 101\n")

4) Working of Append Mode

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 = open("Scholarhat.txt", "a")

file.write("Python is versatile.\n")

file.write("Expand your skills with ScholarHat.\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.

5) Closing Files in Python

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

file = open("Scholarhat.txt", "w")

file.write("This is a new line.\n")

file.close() # Closes the file and saves changes

Implementing All File Handling Functions in Python


This example will cover all of the previously discussed concepts, such as opening, reading,
writing, appending, and closing a file. In addition, we will look at how to delete a file using the
os module's remove() function.

1. File Modes in Python

The open() function in Python is used to open a file, and it supports different modes for different
types of operations.

All File Modes:

Mode Name Description


'r' Read Default mode. Opens file for reading. File must exist.
'w' Write Opens file for writing. Creates file if not exists, overwrites if
exists.
'a' Append Opens file to append data at the end. Creates file if it doesn’t
exist.
'x' Exclusive Creates a new file. Fails if file exists.
Creation
'b' Binary mode Used with other modes to read/write binary files (e.g., images,
videos).
't' Text mode Default. Used with text files.
'r+' Read and Write Reads and writes to file. File must exist.
'w+' Write and Read Writes and reads. Overwrites existing file or creates a new one.
'a+' Append and Read Appends and reads from file. Creates file if not exists.

Text vs Binary Modes

Text Mode (t): Default. Reads/writes strings. Handles character encoding.


Binary Mode (b): Reads/writes bytes. No encoding/decoding. Use for images, PDFs, etc.

2. File Operations in Python

2.1 Create and Write to a File

with open("sample.txt", "w") as file:


file.write("This is the first line.\n")
file.write("This is the second line.\n")

This will:
 Create the file if it doesn't exist.
 Overwrite the file if it does.

2.2 Append Data to a File

with open("sample.txt", "a") as file:


file.write("This is an appended line.\n")

This will:

 Add content to the end without deleting existing content.

2.3 Read Entire File

with open("sample.txt", "r") as file:


content = file.read()
print(content)

This reads everything as a single string.

2.4 Read Line by Line

with open("sample.txt", "r") as file:


for line in file:
print("Line:", line.strip())

// line.strip() removes any leading and trailing whitespace, including newline characters (\n),
making the output cleaner.

Or

with open("sample.txt", "r") as file:


lines = file.readlines() # Returns a list of lines
print(lines)

2.5 Read and Write (r+)

with open("sample.txt", "r+") as file:


file.write("Overwritten content.\n")
file.seek(0)
print(file.read())
 Opens file for both reading and writing.
 Doesn't truncate (delete) existing content unless overwritten.

2.6 Write and Read (w+)

with open("sample.txt", "w+") as file:


file.write("This file is now replaced.\n")
file.seek(0)
print(file.read())

 Clears the file content first (like w), then allows read/write.

2.7 Append and Read (a+)

with open("sample.txt", "a+") as file:


file.write("Another line at the end.\n")
file.seek(0)
print(file.read()) # Will print entire content including new line

2.8 Exclusive Creation (x)

try:
with open("newfile.txt", "x") as file:
file.write("This file is created exclusively.")
except FileExistsError:
print("File already exists.")

 Use to safely create a file. If the file exists, it throws an error.

2.9 Working with Binary Files

Write binary:

with open("image.jpg", "rb") as img:


data = img.read()

with open("copy.jpg", "wb") as img_copy:


img_copy.write(data)

 rb: read binary


 wb: write binary
Used when working with images, audio, videos, PDFs, etc.

2.10 File Object Methods

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

Example: All-in-One File Operation Program

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")

# Read All Lines


with open(filename, "r") as f:
print("Reading file contents:")
for line in f:
print(line.strip())

# Using tell() and seek()


with open(filename, "r") as f:
print("\nCursor at:", f.tell())
content = f.read()
print("Read Content:", content)
f.seek(0)
print("After seek, Cursor at:", f.tell())
Mod Description File Created? Existing Content? Can Read? Can Write?
e
'r' Read No Required ✔️ ❌
'w' Write (overwrite) Yes Overwritten ❌ ✔️
'a' Append Yes Preserved ❌ ✔️
'x' Exclusive creation Yes (only) Error if exists ❌ ✔️
'r+' Read and Write No Required ✔️ ✔️
'w+' Write and Read Yes Overwritten ✔️ ✔️
'a+' Append and Read Yes Preserved ✔️ ✔️

You might also like