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

Text File

The document provides a comprehensive guide on file handling in Python, covering text and binary files, including methods for opening, reading, writing, and closing files. It explains various file access modes and introduces the pickle module for handling binary files through pickling and unpickling processes. Key functions such as read(), write(), tell(), and seek() are detailed for effective file manipulation.

Uploaded by

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

Text File

The document provides a comprehensive guide on file handling in Python, covering text and binary files, including methods for opening, reading, writing, and closing files. It explains various file access modes and introduces the pickle module for handling binary files through pickling and unpickling processes. Key functions such as read(), write(), tell(), and seek() are detailed for effective file manipulation.

Uploaded by

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

FILE HANDLING

Text Files
INTRODUCTION TO FILES

Govindaraja K, Sainik School Kodagu 2


STEPS TO PROCESS A FILE
1. Determine the type of file usage.
a. Reading purpose : If the data is to be
brought in from a file to memory
b. Writing purpose : If the data is to be sent
from memory to file.
2. Open the file and assign its reference to a

file object or file-handle.


3. Process the file as required : Perform the
desired operation from the file.
4. Close the file. 3
OPENING A TEXT FILE

 The key function for working with files in Python is the open()
function.
●It accepts two arguments : filename, and mode.
Syntax:
<file_object_name> = open(<file_name>,<mode>)
Example: f = open(“demo.txt”,”r”)
●Can specify if the file should be handled as binary or text Mode :
 "t" - Text - Default value. Text mode
 "b" - Binary - Binary mode (e.g. images)
Govindaraja K, Sainik School Kodagu 4
OPENING A TEXT FILE

File Objects:
 It serves as a link to file residing in your computer.
 It is a reference to the file on the disk and it is through
this link python program can perform operations on
the files.
File access modes:
 It governs the type of operations(such as read or write
or append) possible in the opened file.
Govindaraja K, Sainik School Kodagu 5
Mode Description

“r” Read Default value. Opens a file for reading,


error if the file does not exist.

“w” Write Opens a file for writing, creates the file if it


does not exist

“a” Append Opens a file for appending, creates the file


if it does not exist

“r+” Read and File must exist otherwise error is


Write raised.Both reading and writing operations Various
can take place.
Modes for
“w+” Write and File is created if it does not exist.If the file
Read exists past data is lost (truncated).Both opening a
reading and writing operations can take
place. text file
are
“a+” Append and File is created if it does not exist.If the file
Read exists past data is not lost .Both reading
and writing(appending) operations can take
place.
6
CLOSING A FILE

close()- method will free up all the system resources used by the file,
this means that once file is closed, we will not be able to use the file
object any more.
<fileobject>. close() will be used to close the file object, once we have
finished working on it.
Syntax:
<fileObject>.close()
Example : f.close()
●It is important to close your files, as in some cases, due to buffering,
changes made to a file may not show until you close the file.
Govindaraja K, Sainik School Kodagu 7
READING FROM A FILE

A Program reads a text/binary file from hard disk. Here


File acts like an input to the program.
Followings are the methods to read a data from the
file:
◆ read() METHOD
◆ readline() METHOD
◆ readlines() METHOD
Govindaraja K, Sainik School Kodagu 8
READ() METHOD

By default the read() method returns the whole text, but you can also specify how
many characters you want to return by passing the size as argument.
Syntax: <file_object>.read([n])
where n is the size
●To read entire file : <file_object>.read()
●To reads only a part of the File : <file_object>.read(size)

f = open("demo.txt", "r")

print(f.read(15))

Returns the 15 first characters of the file "demo.txt".


Govindaraja K, Sainik School Kodagu 9
#To read Entire text from the file

fin=open(r"C:\Users\user-pc\OneDrive\Desktop\marks.txt", "r")
print(fin.read())
fin.close()

10
READLINE() METHOD

• readline() will return a line read, as a string from the file.

Syntax:

<file_object>.readline()
●Example

f = open("demo.txt", "r")

print(f.readline())
●This example program will return the first line in the file
“demo.txt” irrespective of number of lines inGovindaraja
the text file.
K, Sainik School Kodagu 11
READING A
COMPLETE FILE LINE
BY LINE USING
READLINE().

Govindaraja K, Sainik School Kodagu 12


READLINES() METHOD

readlines() method will return a list of strings, each separated by \


n
● readlines() can be used to read the entire content of the file.

Syntax:

<file_object>.readlines()
●It returns a list, which can then be used for manipulation.

Example : f = open("demofile.txt", "r")

print(f.readlines())
Govindaraja K, Sainik School Kodagu 13
Read a file using Readlines()

14
15
WRITING TO A TEXT FILE

• A Program writes into a text/binary file in hard disk.


• Followings are the methods to write a data to the file.
write () METHOD
writelines() METHOD
• To write to an existing file, you must add a parameter
to the open()
• Function which specifies the mode :
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
Govindaraja K, Sainik School Kodagu 16
WRITE() METHOD

• write() method takes a string ( as parameter ) and


writes it in the file.
• For storing data with end of line character, you will have
to add \n character to end of the string
• Syntax:
<fileobject>.write (“Content needs to be stored”)
Or
<fileobject>.write(Variable_Name)

Govindaraja K, Sainik School Kodagu 17


WRITE() METHOD

Open the file "demo_append.txt" and append content to the file:

f = open("demo_write.txt", “w")
f.write("Hello students \n We are learning data file
handling…..!")
f.close()
f = open("demo_write.txt", "r") #open and read the file
after the writting
print(f.read()) Govindaraja K, Sainik School Kodagu 18
Govindaraja K, Sainik School Kodagu 19
WRITELINES() METHOD

• For writing a string at a time, we use write() method, it


can't be used for writing a list, tuple etc. into a file.

• Python file method writelines() writes a sequence of


strings to the file. The sequence can be any iterable object
producing strings, typically a list of strings.
•So, whenever we have to write a sequence of string, we
will use writelines(), instead of write(). Govindaraja K, Sainik School Kodagu 20
Govindaraja K, Sainik School Kodagu 21
SETTING OFFSETS IN A FILE

• Functions used to access the data sequentially from a


file.
• to access data in a random fashion, then Python gives
us
Followings are the methods to random access of
data from the file:
• Govindaraja K, Sainik School Kodagu 22
TELL() METHOD

• tell() method used to determine the current position

or offset within a file.

• It returns the current file position, represented as the

number of bytes from the beginning of the file.

• Syntax: file_object.tell() Govindaraja K, Sainik School Kodagu 23


TELL() METHOD

Open the marks.txt" and find the position to the


file:
fin=open(r"C:\Users\govin\OneDrive\Desktop\
marks.txt", "r")
print(fin.read(5))
position=fin.tell()
print(position)
Govindaraja K, Sainik School Kodagu 24
SEEK() METHOD

• seek() method in Python is used to change the current


position of the file pointer within a file.
• It allows move the pointer to a specific location within the
file, enabling program to read or write data from that
position onwards.
• Syntax: file_object.seek(offset [, reference point])
• offset is the number of bytes by which the file object is
Govindaraja K, Sainik School Kodagu 25
SEEK() METHOD

Reference_point indicates the starting position of the file


object. That is, with reference to which position, the offset
has to be counted.
It can have any of the following values:
0 - beginning of the file
1 - current position of the file
2 - end of file Govindaraja K, Sainik School Kodagu 26
SEEK() METHOD

Open the marks.txt" and moving the file cursor in the file:
print("Learning to move the file object")
fin=open(r"C:\Users\govin\OneDrive\Desktop\marks.txt", "r+")
print(fin.read(5))
position=fin.tell()
print("The position of the file object is",position)
fin.seek(0)
print("Now the file object is at the beginning of the file:",fin.tell())
fin.seek(10)
print("We are moving to 10th byte position from the beginning of file")
print("The position of the file object is at", fin.tell())
str=fin.read()
print(str)
fin.close() Govindaraja K, Sainik School Kodagu 27
THE FLUSH()

The flush function forces the writing of data on disc still


pending on the output buffer.
Syntax : <file_object>.flush()

Govindaraja K, Sainik School Kodagu 28


Govindaraja K, Sainik School Kodagu 29
STANDARD INPUT, OUTPUT, AND
ERROR STREAMS
❏ Keyboard is the standard input device
❏ stdin - reads from the keyboard
❏ Monitor is the standard output device.
❏ stdout - prints to the display
❏ If any error occurs it is also displayed on the monitor and
hence it is also the standard error device.
❏ Same as stdout but normally only for errors (stderr)

The standard devices are implemented as files called streams.


They can be used by importing the sys module.
30
DATA FILE HANDLING IN
BINARY FILES
Files that store objects as some
byte stream are called binary files.

They are encoded in binary format , as a


sequence of bytes.

There is no delimiter to end the


line.

They are directly in the form of


binary, there is no need to translate
them.
They are not in human readable
form and hence difficult to
understand. 31
 Python provides a special module called
pickle module for this.
 PICKLING refers to the process of
converting the structure to a byte.
 stream before writing to a file.

32
 UNPICKLING is used to convert the byte
stream back to the original
 structure while reading the contents of
the file.

33
Before reading
or writing to a
It provides two
file, we must import pickle
main methods :
import the
pickle module.
dump() load()
method method

PICKLE MODULE

34
Opening a binary file:
Like text file except that it should
be opened in binary mode.
Adding a ‘b’ to the text file mode
OPENING makes it binary - file mode.
BINARY Syntax:
FILES
Fileobject=open(“filename’,
“rb”)
EXAMPLE :
f=
open(“demo.dat”,”rb”) 35
Closing a binary file
CLOSING
BINARY fileobject . close()
FILES

36
Mode Description

“rb” Read Default value. Opens a file for


reading, error if the file does not
exist.
“wb” Write Opens a file for writing, creates
the file if it does not exist
“ab” Append Opens a file for appending,
Different Modes of creates the file if it does not exist
Binary Files “r+b” Read and File must exist otherwise error is
or Write raised. Both reading and writing
“rb+” operations can take place.
“w+b” Write and File is created if it does not exist.
or Read If the file exists past data is lost
“wb+” (truncated).Both reading and
writing operations can take place.
“a+b” Append File is created if it does not exist.If
or and Read the file exists past data is not
“ab+” lost .Both reading and writing
operations can take place. 37
 pickle.dump() method is used to
write the object in file which is
opened in binary access mode.
 Syntax :
 pickle.dump(<structure>,<Fileob
PICKLE.DUM
P() METHOD ject>)
 Structure can be any sequence in
Python such as list, dictionary etc.

 Fileobject is the file handle of file in


which we must write. 38
# Demonstration of dump() in Python
import pickle
print("Demonstration of demp() method")
fin=open(r"C:\Users\govin\OneDrive\Desktop\
dump1.data","wb")
city=["Kushalnagar", "Kodagu", "Madikeri"]
pickle.dump(city, fin)
fin.close()
Dump1.data file
after execution of
the program.

39
 pickle.load() method is used to
read data from a file
 Syntax :

PICKLE.LOA  <structure> =
D() METHOD pickle.load(<FileObject>)
 Structure can be any sequence in
Python such as list, dictionary etc.
 FileObject is the file handle of file
in which we have to write.

40
# Demonstration of dump() in Python
import pickle
print("Demonstration of demp() method")
fin=open(r"C:\Users\govin\OneDrive\Desktop\dump1.data","rb")
city=pickle.load(fin)
print(city)
fin.close()

41
PICKLING
AND
UNPICKLING

42
Thank you

43
Govindaraja K, Sainik School Kodagu

You might also like