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

UNIT-V - Part-2 (Files)

This document provides an overview of file handling in Python, detailing the types of files (text and binary), their characteristics, and the methods for creating, reading, writing, and closing files. It explains the importance of file modes, encoding (specifically UTF-8), and additional file operations such as tell(), seek(), and rename(). The content is aimed at enhancing problem-solving skills through effective file management in Python programming.

Uploaded by

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

UNIT-V - Part-2 (Files)

This document provides an overview of file handling in Python, detailing the types of files (text and binary), their characteristics, and the methods for creating, reading, writing, and closing files. It explains the importance of file modes, encoding (specifically UTF-8), and additional file operations such as tell(), seek(), and rename(). The content is aimed at enhancing problem-solving skills through effective file management in Python programming.

Uploaded by

bharath.vfstr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Python Programming for Problem

Solving

Unit-5: Files

Mr. N. Bharath Kumar


Assistant Professor
Department of EEE

Department of Electrical and Electronics Engineering N. Bharath Kumar1


Files

• File is a named location on disk to store related information.


• It is used to permanently store data in a non-volatile
memory (e.g. hard disk).
• Since, random access memory (RAM) is volatile which loses
its data when computer is turned off, we use files for future
use of the data by permanently storing them.
• In Python files can be of two types
1. Text Files
2. Binary Files

Department of Electrical and Electronics Engineering N. Bharath Kumar


Text Files

• Text files are structured as a sequence of lines, where each


line includes a sequence of characters.
• Each line is terminated with a special character, called the
EOL or End of Line character.
• Common extensions that are text file formats are:
• Web standards: html, xml, css, ...
• Source code: c, cpp, java, pl, php, , ...
• Documents: txt, tex, rtf, ps, ...
• Tabular data: csv, tsv, ...

Department of Electrical and Electronics Engineering N. Bharath Kumar


Binary Files
• Binary files are any files where the format isn't made up of
readable characters.
• Binary files can range from image files like JPEGs or GIFs, audio
files like MP3s or binary document formats like Word or PDF.
• Binary files can only be processed by an application that know or
understand the file’s format.
• Common extensions that are binary file formats are:
• Images: jpg, png, gif, bmp, tiff, ...
• Videos: mp4, avi, mov, mpg, ...
• Audio: mp3, wav, wma, ...
• Archive: zip, rar, 7z, tar, ...
• Executable: exe, dll, so, class, ...

Department of Electrical and Electronics Engineering N. Bharath Kumar


Binary Files
• Binary files are any files where the format isn't made up of
readable characters.
• Binary files can range from image files like JPEGs or GIFs, audio
files like MP3s or binary document formats like Word or PDF.
• Binary files can only be processed by an application that know or
understand the file’s format.
• Common extensions that are binary file formats are:
• Images: jpg, png, gif, bmp, tiff, ...
• Videos: mp4, avi, mov, mpg, ...
• Audio: mp3, wav, wma, ...
• Archive: zip, rar, 7z, tar, ...
• Executable: exe, dll, so, class, ...

Department of Electrical and Electronics Engineering N. Bharath Kumar


File Handling in Python
• File handling is an important part of any web application.

• Python has several functions for creating, reading, updating,


and deleting files.

• In Python, a file operation takes place in the following order:


• Open a file
• Read or write (perform operation)
• Close the file

Department of Electrical and Electronics Engineering N. Bharath Kumar


File Handling in Python
Open a File:
• Python has a built-in open() function to open a file.
• This function returns a file object, also called a handle, as it is used to read or modify
the file accordingly.
Syntax: handle = open(filename, mode)
filename: name of the file you want to open
mode: it specifies the type of handling a file
• We can specify the mode while opening a file. In mode, we specify whether we want
to read r, write w or append a to the file. We can also specify if we want to open the
file in text mode or binary mode.
• The default is reading in text mode. In this mode, we get strings when reading from
the file.
• On the other hand, binary mode returns bytes and this is the mode to be used when
dealing with non-text files like images or executable files.

Department of Electrical and Electronics Engineering N. Bharath Kumar


File Handling in Python
Modes for Opening a File:
Mode Description
r Opens a file for reading. (default)
Opens a file for writing. Creates a new file if it does not exist or truncates the
w
file if it exists.
Opens a file for exclusive creation. If the file already exists, the operation
x
fails.

Opens a file for appending at the end of the file without truncating it.
a
Creates a new file if it does not exist.

t Opens in text mode. (default)


b Opens in binary mode.
+ Opens a file for updating (reading and writing)
Department of Electrical and Electronics Engineering N. Bharath Kumar
File Handling in Python
Close a File:
• Python has a built-in close() function to close a file.
• When we are done with performing operations on the file, we need to properly close
the file. Closing a file will free up the resources that were tied with the file.
Syntax: fileObject.close()
Ex: f = open("foo.txt", "wb")
print("Name of the file: ", f.name)
f.close()
• This method is not entirely safe. If an exception occurs when we are performing some
operation with the file, the code exits without closing the file.
• A safer way is to use a try...finally block. This way, we are guaranteeing that the file is
properly closed even if an exception is raised that causes program flow to stop.
• The best way to close a file is by using the with statement. This ensures that the file is
closed when the block inside the with statement is exited. We don't need to explicitly
call the close() method. It is done internally.

Department of Electrical and Electronics Engineering N. Bharath Kumar


File Handling in Python
Close a File:
Using try…finally:

try:
f = open("test.txt", encoding = 'utf-8')
# perform file operations
finally:
f.close()

Using with statement:

with open("test.txt", encoding = 'utf-8') as f:


# perform file operations

Department of Electrical and Electronics Engineering N. Bharath Kumar


File Handling in Python
What is ‘UTF-8’:
• UTF stands for Unicode Transformation Format.
• It refers to several types of Unicode character encodings, including UTF-7, UTF-8, UTF-
16, and UTF-32. .
• UTF-8 is an encoding system for Unicode. It can translate any Unicode character to a
matching unique binary string, and can also translate the binary string back to a
Unicode character.
• UTF-8 is backwards compatible with ASCII. UTF-8 is the preferred encoding for e-mail
and web pages.
• Unlike other languages, the character a does not imply the number 97 until it is
encoded using ASCII (or other equivalent encodings). Hence, when working with files
in text mode, it is highly recommended to specify the encoding type.

Ex: f = open("test.txt", mode='r', encoding='utf-8')

Department of Electrical and Electronics Engineering N. Bharath Kumar


File Handling in Python
Writing to Files:
• Python has a built-in write() function that writes any string to an open file.
• In order to write into a file in Python, we need to open it in write w, append a or
exclusive creation x mode.
Syntax: fileObject.write(string)
Ex: with open("test.txt",'w',encoding = 'utf-8') as f:
f.write("my first file\n")
f.write("This file\n\n")
f.write("contains three lines\n")
• This program will create a new file named test.txt in the current directory if it does
not exist. If it does exist, it is overwritten.
• We need to be careful with the w mode, as it will overwrite into the file if it already
exists. Due to this, all the previous data are erased.
• The write() method does not add a newline character ('\n') to the end of the string.
We must include the newline characters ourselves to distinguish the different lines.

Department of Electrical and Electronics Engineering N. Bharath Kumar


File Handling in Python
Read a File:
• Python has a built-in read() function that reads a string from an open file.
• To read a file in Python, we must open the file in reading r mode.
• To open a file for reading it is enough to specify the name of the file.
Syntax: f = open("demofile.txt")
• The code above is the same as:
Syntax: f = open("demofile.txt“, rt)
• Because "r" for read, and "t" for text are the default values, you do not need to
specify them.
• Note: Make sure the file exists, or else you will get an error.
Ex: f = open("demofile.txt", "r")
print(f.read())
• If the file is located in a different location, you will have to specify the file path.
Ex: f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())
• The read() method returns a newline as '\n'. Once the end of the file is reached, we
get an empty string on further reading.
Department of Electrical and Electronics Engineering N. Bharath Kumar
File Handling in Python
Read a File:
• By default the read() method returns the whole text, but you can also specify how
many characters you want to return.
Ex: f = open("demofile.txt", "r")
print(f.read(5))
• You can return one line by using the readline() method.
Ex: f = open("D:\\myfiles\welcome.txt", "r")
print(f.readline())
• By calling readline() two times, you can read the two first lines.
Ex: f = open("D:\\myfiles\welcome.txt", "r")
print(f.readline())
print(f.readline())
• By looping through the lines of the file, you can read the whole file, line by line.
Ex: f = open("D:\\myfiles\welcome.txt", "r")
for x in f:
print(x)

Department of Electrical and Electronics Engineering N. Bharath Kumar


File Handling in Python
Create a New File:

• To create a new file in Python, use the open() method, with one of the
following parameters:
• "x" - Create - will create a file, returns an error if the file exist
• "a" - Append - will create a file if the specified file does not exist
• "w" - Write - will create a file if the specified file does not exist.

Ex:
f=open("myfile.txt", "x")
f=open("myfile.txt", "w")
f=open("myfile.txt", “a")

Department of Electrical and Electronics Engineering N. Bharath Kumar


Other operations on Files
tell():

• The method tell() returns the current position of the file read/write pointer
within the file.
Syntax: fileObject.tell()
Ex:
f= open('one.txt','r')
print(f.readline())
print(f.tell())

o/p:
Hi this is cse
16

Department of Electrical and Electronics Engineering N. Bharath Kumar


Other operations on Files
seek():
• It is used to change the file pointer position.
• The method seek() sets the file's current position at the offset.
Syntax: fileObject.seek(offset, [whence])
offset − This is the position of the read/write pointer within the file.
whence − This is optional and defaults to 0 which means absolute file
positioning, other values are 1 which means seek relative to the current
position and 2 means seek relative to the file's end.

Ex:
f= open('one.txt','r')
print(f.readline()) #o/p: hi this is cse
f.seek(3,0)
print(f.readline()) #o/p: this is cse

Department of Electrical and Electronics Engineering N. Bharath Kumar


Other operations on Files
rename():

• rename() method is used to rename a file or directory.


• This method is a part of the os module.

Syntax:
os.rename(oldname,newname)

Ex:
import os
os.rename("one2.txt","two.txt")

Department of Electrical and Electronics Engineering N. Bharath Kumar

You might also like