0% found this document useful (0 votes)
5 views12 pages

Python File Handling Techniques

This document outlines a Python lesson focused on file handling, including reading and writing files, and converting dictionaries to CSV files. It covers the types of files in Python, operations for file handling, and the use of context managers for resource management. Additionally, it provides a problem-solving exercise related to counting word occurrences in a text file.

Uploaded by

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

Python File Handling Techniques

This document outlines a Python lesson focused on file handling, including reading and writing files, and converting dictionaries to CSV files. It covers the types of files in Python, operations for file handling, and the use of context managers for resource management. Additionally, it provides a problem-solving exercise related to counting word occurrences in a text file.

Uploaded by

cvnkjqkbwd
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON

LESSON 5

CFGDEGREE → FOUNDATION MODULE


AGENDA

01 File handling

02 Reading and writing files

03 Converting dictionaries into csv files

04 Problem solving with Python


PYTHON FILE HANDLING
IMPORTANT POINTS # TYPES OF FILES IN PYTHON

● Imagine, we are creating a program that ● Binary file


works with a large amount of data
● We cannot expect that data to be stored in
a variable as the variables are volatile in ● Text file
nature.
● The data is stored externally, for example a
file
● As files are non-volatile in nature, the data
will be stored permanently and using
python we will handle these files in our
applications.
BINARY FILES IN PYTHON
IMPORTANT POINTS # EXAMPLE BINARY FILES

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


● We can open some binary files in the ● Image files: .png, .jpg, .gif, .bmp etc.
normal text editor but we CANNOT ● Video files: .mp4, .3gp, .mkv, .avi etc.
read the content present inside the ● Audio files: .mp3, .wav, .mka, .aac etc.
file. ● Database files: .sql, .accde, .frm, .sqlite etc.
● Archive files: .zip, .rar, .iso, .7z etc.
● Executable files: .exe, .dll, .class etc.
● All the binary files will be ENCODED in
the binary format, which can be
understood only by a computer or
machine.
TEXT FILES IN PYTHON
IMPORTANT POINTS # TEXT FILES IN PYTHON

● Text files do not have any specific ● Web standards: html, XML, CSS, JSON etc.
encoding and it can be opened in ● Source code: c, app, js, py, java etc.
normal text editor itself. ● Documents: txt, tex, RTF etc.
● Tabular data: csv, tsv etc.
● Configuration: ini, cfg, reg etc.
FILE HANDLING OPERATIONS
DEFINITION # EXAMPLE CREATE & OPEN FILE
Most common

● open / read / write / close


file_object =
Other open(file_name, mode)
● rename / delete

Mode

● ‘r’ – Read Mode


● ‘w’ – Write Mode
● ‘a’ – Append Mode
● ‘r+’ – Read or Write Mode (same file)
● ‘a+’ – Append or Read Mode (same file)
for BINARY files use the same modes with the letter ‘b’ at the end.

'rb' or 'wb' and so on


READING FROM A FILE
DEFINITION # EXAMPLE

● In order to read a file in python, read()


we must open the file in read
readline()
mode.
readlines()
● There are three ways in which
we can read the files in python. What is the difference?
WRITE TO A FILE
DEFINITION # EXAMPLE

● we need to open or create a new file

● write a line or lines into the new file


See DEMO(s)

● once finished, then we must close the


file to save the changes
CONTEXT MANAGER
PYTHON DATA TYPE # EXAMPLE

● Context managers facilitate the with open('[Link]', 'w+') as text_file:


proper handling of resources.
people = 'Joanne \nSusan \nAmina'

text_file.write(people)
● In the case of performing file
operations a context manager ---------------------------------------------------------------------------
would automatically open and
close the file for us. with open('[Link]', 'r') as text_file:
contents = text_file.read()

● The syntax is slightly different, it print(contents)


uses the with word. We can call it
a with block
WORKING WITH CSV FILES
IN PYTHON # EXAMPLE

● csv is a Python library that


simplifies reading and writing
tabular text from/to a csv file. See DEMO(s) &
Complete EXERCISE(s)
● The library needs to be
imported first to be able to
access its functions and
objects.
PROBLEM SOLVING
IN PYTHON # EXAMPLE STEPS

Write a Python program to count the 1. Take the file name and the word to be
occurrences of a word in a text file counted from the user.
● Your program will take a word from 2. Read each line from the file and split
the user and count the number of the line to form a list of words.
occurrences of that word in a file. 3. Check if the word provided by the user
and any of the words in the list are
equal and if they are, then increment
the word count.
4. Exit
THANK YOU!

Common questions

Powered by AI

Closing files after operations is crucial to free up system resources and prevent file corruption or data inconsistency. Python's context managers simplify this task by automatically closing files at the end of a block of code, ensuring that no resources remain unnecessarily occupied .

Converting dictionaries to CSV files allows for efficient storage and manipulation of tabular data. The csv library in Python supports reading from and writing to CSV files, facilitating data exchange between programs that process tabular data formats for analysis or visualization .

Python can handle both binary and text files. Binary files, such as .pdf, .png, and .mp4, are encoded in binary format and cannot be read directly via a normal text editor; they are meant to be understood by machines . Text files, on the other hand, do not have specific encoding, and their contents can be readily viewed and edited using text editors; they include formats like txt, csv, and ini .

Python provides three methods for reading from a file: read(), readline(), and readlines(). The read() method reads the entire file content as a single string, readline() reads one line at a time, and readlines() reads all the lines into a list where each element represents a line in the file .

Web standard files such as HTML, XML, CSS, and JSON are text files and are typically opened in standard text editors without specific encoding, allowing for easy viewing and editing. Tabular data files like csv and tsv are also text files but are structured such that they represent data in a table format and often require libraries such as csv in Python to effectively parse and manage the tabular data .

The 'with' keyword in Python simplifies file handling by automatically managing file opening and closing within a block of code. This ensures resources are released properly, preventing potential resource leaks and enhancing code reliability and maintainability. It also makes code cleaner and less error-prone, as manual closure is not needed .

Files in Python can be opened in different modes: 'r' for read, 'w' for write, 'a' for append, 'r+' for read/write, and 'a+' for append/read. When dealing with binary files, the same modes can be applied with a 'b' appended, such as 'rb' and 'wb', to indicate that the file is a binary file .

Opening binary files with a text editor poses challenges because binary files are encoded in a format meant for computer processing and not human readability. Consequently, attempting to open them with a text editor often results in unreadable characters, as the editor cannot interpret the binary encoding .

To count occurrences of a word in a text file in Python, first prompt the user for the file name and the target word. Read the file line-by-line, splitting each line into a list of words. Compare each word to the target word and increment a counter whenever a match is found. This approach involves iterating over the lines and words within the file .

Context managers streamline resource handling in Python by ensuring that files are properly opened and closed without explicit user instructions. By using the 'with' keyword, context managers automatically manage resources, thereby preventing resource leaks and ensuring that files are always closed after operations are performed on them .

You might also like