MODULE-4
File and I/O
CONTENT
Files and I/O
Reading and Writing Text Data, Printing to a File, Reading and Writing
Binary Data.
Filenames, Adding or Changing the Encoding of an Already Open File,
Writing Bytes to a Text File.
Writing CSV Data, Reading and Writing JSON Data.
FILE OPERARTIONS
File operations in any programming is very essential. Files are used to
save and transfer data. They can be of any form, a text file or a media
file.
File handling is basically the management of the files on a file system.
Every operating system has its own way to store files.
READING AND WRITING TEXT DATA
Text
Binary
CSV
Json
WHEN TO USE FILE HANDLING IN
PYTHON
Storing and Retrieving Data
Processing Large Files
Managing Configuration and Log Files
FILE HANDLING METHODS
Python provides built-in methods for efficient file operations.
read(size): Reads the specified number of bytes.
readline(): Reads one line at a time.
readlines(): Reads all lines and returns a list.
write(string): Writes a string to the file.
writelines(list): Writes multiple lines at once.
seek(offset): Moves the cursor to a specific position.
tell(): Returns the current cursor position.
MODE OF FILE HANDLING
Using the correct file mode ensures smooth file operations.
'r' allows safe file reading.
'w' creates or overwrites a file.
'a' appends data without modifying existing content.
'rb' and 'wb' handle binary files.
WORKING WITH BINARY FILES
Binary files store non-text content like images, audio, and videos.
Use and modes to read and write them.
'rb' 'wb'
CSV FILE
The so-called CSV (Comma Separated Values) format is the most common
import and export format for spreadsheets and databases.
import csv
with open('[Link]', newline='') as csvfile:
spamreader = [Link](csvfile, delimiter=' ', quotechar='|')
for row in spamreader:
print(', ‘.join(row))
OPERATION
1. [Link](csvfile, /, dialect='excel', **fmtparams)
2. [Link](csvfile, /, dialect='excel', **fmtparams)
import csv
with open('[Link]', newline='') as f:
reader = [Link](f)
for row in reader:
print(row)
JSON
Python’s json module provides you with the tools you need to effectively handle
JSON data.
You can convert Python data types to a JSON-formatted string
with [Link]() or write them to files using [Link]().
Similarly, you can read JSON data from files with [Link]() and parse JSON
strings with [Link]().
The acronym JSON stands for JavaScript Object Notation. As the name suggests,
JSON originated from JavaScript.
However, JSON has transcended its origins to become language-agnostic and is
now recognized as the standard for data interchange.
The act of converting data into the JSON format is referred to as serialization.
This process involves transforming data into a series of bytes for storage or transmission
over a network.
The opposite process, deserialization, involves decoding data from the JSON format back into
a usable form within Python.
>>> import json
>>> food_ratings = {"organic dog food": 2, "human food": 10}
>>> [Link](food_ratings)
'{"organic dog food": 2, "human food": 10}’
WRITE JSON FILE
import json
dog_data = {
"name": "Frieda",
"is_dog": True,
"hobbies": ["eating", "sleeping", "barking",],
"age": 8,
"address": {
"work": None,
"home": ("Berlin", "Germany",),
},
"friends": [
"name": "Philipp",
"hobbies": ["eating", "sleeping", "reading",],
},
"name": "Mitch",
"hobbies": ["running", "snacking",],
},
],
}
The [Link]() function has two required arguments:
The object you want to write
The file you want to write into
[Link](): To deserialize a string, bytes, or byte array instances
[Link](): To deserialize a text file or a binary file
JSON TO PYTHON