0% found this document useful (0 votes)
6 views

file_handling_notes

Uploaded by

ssanth561
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

file_handling_notes

Uploaded by

ssanth561
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Chapter 3

File Handling
Introduction to Files in Python

In Python, files are used to store data persistently. Files can contain any kind of data, and you
can use Python to read from and write to files. There are various types of files that you might
encounter, including text files, binary files, and CSV files.

Types of Files

1. Text Files: Text files contain plain text and are typically human-readable. They use character
encoding, such as ASCII or UTF-8, to store text data.
Examples: .txt, .csv, .html
Usage: You can open text files in different modes like r (read), w (write), a (append), etc.

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


content = file.read()
print(content)

2. Binary Files: Binary files store data in binary format, which is not human-readable. They can
store any type of data, including images, audio, video, and more.
Examples: .jpg, .png, .exe, .dat
Usage: You use the rb (read binary) or wb (write binary) modes to handle binary files.

with open('example.jpg', 'rb') as file:


content = file.read()

3. CSV Files: CSV (Comma-Separated Values) files are a special type of text file where data is
organized in rows and columns. Each line in the file corresponds to a row, and values within a
row are separated by commas.
Examples: .csv
Usage: Python provides the csv module to work with CSV files easily.

import csv
with open('example.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)

Relative and Absolute Paths


Absolute Path:An absolute path specifies the full path to a file or directory from the root
directory. It is a complete address, starting from the root (e.g.,
C:\Users\Name\Documents\file.txt on Windows or /home/user/file.txt on Linux/Mac).

Example:
file_path = "/home/user/documents/example.txt"
with open(file_path, 'r') as file:
content = file.read()

Relative Path:A relative path specifies the location of a file or directory relative to the current
working directory. It does not start from the root directory but from the current directory.
Example:

file_path = "documents/example.txt"
with open(file_path, 'r') as file:
content = file.read()

Handling Text Files in Python

1. Opening a Text File


To open a text file in Python, use the `open()` function, which requires the file path and the
mode in which you want to open the file.

file = open('example.txt', 'r')

2. Text File Open Modes


- `r` (Read): Opens the file for reading. The file pointer is placed at the beginning of the file. If
the file does not exist, an error is raised.

file = open('example.txt', 'r')

- `r+` (Read and Write): Opens the file for both reading and writing. The file pointer is placed at
the beginning of the file. If the file does not exist, an error is raised.

file = open('example.txt', 'r+')

- `w` (Write): Opens the file for writing only. If the file exists, it truncates the file to zero length
(i.e., deletes the content). If the file does not exist, it creates a new file.

file = open('example.txt', 'w')


- `w+` (Write and Read): Opens the file for both writing and reading. It truncates the file if it
exists and creates a new file if it doesn't.

file = open('example.txt', 'w+')

- `a` (Append): Opens the file for writing. The file pointer is placed at the end of the file if it
exists. It creates a new file if it doesn't exist.

file = open('example.txt', 'a')

- `a+` (Append and Read): Opens the file for both appending and reading. The file pointer is
placed at the end of the file. It creates a new file if it doesn't exist.

file = open('example.txt', 'a+')

3. Closing a Text File


Always close a file after you’re done with it using the `close()` method to free up system
resources.

file = open('example.txt', 'r')


# Perform file operations
file.close()

4. Opening a File Using `with` Clause


Using the `with` clause is the preferred way to open files in Python as it automatically closes
the file after the block of code is executed.

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


content = file.read()

5. Writing/Appending Data to a Text File


- Using `write()`: Writes a string to the file.

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


file.write("Hello, world!")

- Using `writelines()`: Writes a list of strings to the file.

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


lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
file.writelines(lines)

- Appending Data: You can append data to a file using the `a` or `a+` mode.
with open('example.txt', 'a') as file:
file.write("This is an appended line.\n")

6. Reading from a Text File

- Using `read()`: Reads the entire file content as a string.

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


content = file.read()
print(content)

- Using `readline()`: Reads one line at a time from the file.

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


line = file.readline()
while line:
print(line, end=' ')
line = file.readline()

- Using `readlines()`: Reads all the lines of a file and returns them as a list of strings.

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


lines = file.readlines()
for line in lines:
print(line, end='')

7. `seek()` and `tell()` Methods


- `seek()`: Moves the file pointer to a specified position.

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


file.seek(5) # Move the pointer to the 6th character as index starts from 0
content = file.read()
print(content)

- `tell()`: Returns the current position of the file pointer.

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


content = file.read(10) # Read first 10 characters
position = file.tell()
print("Current file pointer position:", position)

8. Manipulation of Data in a Text File


You can manipulate data by reading from a file, modifying the data, and writing it back to the
file.
with open('example.txt', 'r+') as file:
content = file.read()
modified_content = content.replace('world', 'Python')
file.seek(0)
file.write(modified_content)
file.truncate()

Handling Binary Files in Python

Binary files store data in a binary format, which is not human-readable. These files are handled
differently than text files in Python.

Basic Operations on a Binary File

1. Opening a Binary File


- Binary files are opened using different modes, depending on the operation you want to
perform.

- File Open Modes:


- `rb`: Open for reading in binary mode.
- `rb+`: Open for reading and writing in binary mode.
- `wb`: Open for writing in binary mode. If the file exists, it is truncated. If the file does not
exist, it is created.
- `wb+`: Open for reading and writing in binary mode. If the file exists, it is truncated. If the
file does not exist, it is created.
- `ab`: Open for appending in binary mode. The file pointer is at the end of the file if the file
exists. If the file does not exist, it is created.
- `ab+`: Open for reading and appending in binary mode. The file pointer is at the end of the
file if the file exists. If the file does not exist, it is created.

Example

with open(“example.bin”, “wb”) as binary_file:


# Write binary data here
Pass

2. Closing a Binary File


- Always close the binary file after performing operations on it to free up resresources

binary_file.close()

3. Importing the `pickle` Module


- The `pickle` module is used for serializing and deserializing Python objects.
- Serializing is the process of converting a Python object into a byte stream.
- Deserializing is the process of converting a byte stream back into a Python object.

import pickle

4. `dump()` and `load()` Methods


- `dump()`: Used to write a Python object to a binary file.

with open(“example.bin”, “wb”) as binary_file:


data = {“name”: “Alice”, “age”: 25}
pickle.dump(data, binary_file)

- `load()`: Used to read a Python object from a binary file.

with open(“example.bin”, “rb”) as binary_file:


data = pickle.load(binary_file)
Print(data) # Outputs: {‘name’: ‘Alice’, ‘age’: 25}

Operations in a Binary File

1. Read
- Reading from a binary file can be done using the `load()` method from the `pickle` module.

with open(“example.bin”, “rb”) as binary_file:


data = pickle.load(binary_file)
print(data)

2. Write/Create
- Writing to a binary file can be done using the `dump()` method.

with open(“example.bin”, “wb”) as binary_file:


data = {“name”: “Bob”, “age”: 30}
pickle.dump(data, binary_file)

3. Search
- To search for specific data in a binary file, you need to load the data and then search within
the loaded object.

with open(“example.bin”, “rb”) as binary_file:


data = pickle.load(binary_file)
if “name” in data:
print(“Name found:”, data[“name”])

4. Append
- To append data to a binary file, open it in `ab` or `ab+` mode and then write the additional
data.

with open(“example.bin”, “ab”) as binary_file:


additional_data = {“city”: “New York”}
pickle.dump(additional_data, binary_file)

5. Update
- Updating involves reading the data, modifying it, and then writing it back to the file.

# Read the current data


with open(“example.bin”, “rb”) as binary_file:
data = pickle.load(binary_file)

# Update the data


data[“age”] = 31

# Write the updated data back


with open(“example.bin”, “wb”) as binary_file:
pickle.dump(data, binary_file)

Handling CSV Files in Python

1. Importing the CSV Module


To work with CSV files in Python, you first need to import the csv module.

import csv

2. Opening and Closing a CSV File


Opening a CSV File: Use the open() function to open a CSV file. You can specify the mode ('r'
for reading, 'w' for writing, etc.).Closing a CSV File: After completing the operations on the file,
close it using the close() method to ensure all resources are freed.

file = open('example.csv', 'w', newline='')


# Performing operations on the file
# Closing the file
file.close()
3. Writing to a CSV File
To write data into a CSV file, you can use the csv.writer() method, along with writerow() and
writerows().

csv.writer(): Creates a writer object that converts data into a delimited string format.
writerow(): Writes a single row of data to the CSV file.
writerows(): Writes multiple rows of data to the CSV file at once.

with open('example.csv', 'w', newline='') as file:


writer = csv.writer(file)

# Writing a single row


writer.writerow(['Name', 'Age', 'Country'])

# Writing multiple rows


writer.writerows([
['Alice', 30, 'USA'],
['Bob', 25, 'Canada'],
['Charlie', 35, 'UK']
])

4. Reading from a CSV File


To read data from a CSV file, you can use the csv.reader() method.

csv.reader(): Creates a reader object that iterates over lines in the CSV file.

with open('example.csv', 'r') as file:


reader = csv.reader(file)
# Iterating over rows in the CSV file
for row in reader:
print(row)

You might also like