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

Text File Notes

1. A data file is a stream of data stored on disk with a file name that allows storing and retrieving related data. 2. File handling in Python allows reading from and writing to disk files, allowing data to be permanently stored and accessed later. 3. Files provide a way for programs to communicate with external data and access stored data even after closing the program.

Uploaded by

randomotaku780
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)
17 views

Text File Notes

1. A data file is a stream of data stored on disk with a file name that allows storing and retrieving related data. 2. File handling in Python allows reading from and writing to disk files, allowing data to be permanently stored and accessed later. 3. Files provide a way for programs to communicate with external data and access stored data even after closing the program.

Uploaded by

randomotaku780
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
You are on page 1/ 25

1

Lesson – 4 – Data File


Handling
Sept 2023

Learning Objective : To interface Python with Data Files


FILE
• A data file is a stream (sequence) of data occupying named place (File name) on the disk where a
sequence of related data is stored.
• A document / data stored on permanent storage device.
• Data is packaged up on the storage device as data structures called Files.

FILE HANDLING
• A mechanism by which we can read data from a disk file to the python program or write back data from
python program to disk files.
• File handling allows us to store data entered through python program permanently in disk file and can
be retrieved later.

NEED FOR A DATA FILE


• File allows us to access ‘stored’ data even after we close our programs.
• Files provide a means of communication between the program and the outside world.
Learning Objective : To interface Python code to Data Files 2
TEXT FILES
• Text file stores information in ASCII OR UNICODE character.
• In text file all data is stored as a character.
Eg : “Python” occupies 6 bytes
12345.678 occupies 9 bytes

• Each line in Text File is terminated by special character called EOL character. In
text file some translation takes place when this EOL character is read or written.
• In python EOL is ‘\n’ or ‘\r’ or combination of both
NB : ‘\n’ – New Line , ‘\r’ – Carriage Return

Learning Objective : To interface Python code to Data Files


4

OPEN FILE – Using function open( )


• The open( ) functions takes two parameters - Filename & Mode
• open( ) function returns a file object.
• Syntax: file_objectname= open(filename, mode)

Eg : f1 = open(“Subjects.txt”, “r”)

Learning Objective : To interface Python code to Data Files


5

open( ) File using with statement


• The with statement will automatically close the file after the nested block of code.
• Syntax :
with open (<filename> ,<mode>) as <file_object> :

Learning Objective : To interface Python code to Data Files


6

Modes to Open a File


Text File Mode
Description If file does not exists

r Read - Default value. Opens a file for reading, ERROR


w Write - Opens a file for writing CREATES FILE
a Append - Opens a file for appending, CREATES FILE
r+ Read and Write ERROR
w+ Read and Write CREATES FILE
a+ Read and write CREATES FILE

Learning Objective : To interface Python code to Data Files


7

CLOSE FILE – Using function close( )


• The file has to be closed after the Operations.
• A close( ) function is used to close a file.
• close( ) breaks the link between the file object & the file on the disk.
• Syntax : file-objectname.close( )

Eg : f1.close( )

Learning Objective : To interface Python code to Data Files


8

READ FROM FILE – read( ), readline( ), readlines( )


read () readline( ) readlines( )
• Reads at most ‘n’ bytes • Reads a line of input. • Reads all the lines of the Text File.
• If ‘n’ not mentioned, then • Returns a string ending with ‘\n’. • Returns a List of Strings.
reads the whole file. • If ‘n’ specified then returns ‘n’ no of • If ‘n’ specified then
bytes, but not more than the
• Returns a string • if n < remaining no of characters in
present line.
the present line – Present lin eis
returned
• Else if n> remaining no of
characters in present line – next line
is also returned.

Learning Objective : To interface Python code to Data Files


ACTIVITY
• Create a Text File & use the different read functions and display data.

Learning Objective : To interface Python code to Data Files


Write function
ACTIVITY D.1 definitions in NB

1. Given a Text File ‘poem.txt’ with the Poem ‘Stopping by Woods on a Snowy Evening’ by Robert Frost.
Write function definition to :
a) Count no of dots '.’

b) Count word ‘I’


c) Display lines starting with ‘t’ or ‘T’
d) Display the first & last line
e) Display the longest line

Learning Objective : To interface Python code to Data Files


Learning Objective : To interface Python code to Data Files
12

Properties of File Object


A file object has the following properties :
• name : Name of Opened File
• mode : Mode in which file gets opened.
• closed : Returns Boolean value, True – if file is closed ; False if file is open
• readable( ) : Returns True – if file is readable ; False if file is not readable

Learning Objective : To interface Python code to Data Files


13

WRITE TO FILE – write( ) method


• To write to a file , it must be opened in write ‘w’ or append ‘a’ mode or read-write ‘r+’ mode.
• There are 2 ways to write to a file:
1. write ( ) - Inserts a string as a single line in the Text File ; Syntax – fileobject.write(data)

Learning Objective : To interface Python code to Data Files


WRITE TO FILE – writelines( ) method
• writelines() – To write a Sequence data type (list , tuple). Syntax : fileobj.writelines(list/tuple)

14
RECORD FILE – D.2
Write function definitions to :
a) Create a Text File ‘Cities’ and enter the names of Cities.
b) Display the contents of the file
c) Display the no of occurrences of vowels and consonants.
d) Create a new file 'ACities.txt'and copy the names of cities starting with 'A'.
e) Replace every occurrence of alphabet 'i' with '!' in 'Cities.txt'.

Learning Objective : To interface Python code to Data Files


Learning Objective : To interface Python code to Data Files
The truncate() method resizes
the file to the given number of
bytes.
If the size is not specified, the
current position will be used.

Learning Objective : To interface Python code to Data Files


FILE POINTER
Every file maintains a file pointer which tells the current position in the file.
The file pointer is like a cursor which defines where reading and writing operation will
take.
When we perform any read/write operation two things happens:
The operation at the current position of file pointer (eg:- readline() – reads the line)
File pointer advances by the specified number of bytes. (eg:- readline() takes file pointer till the end of
line)

NB: By default, the file pointer progresses sequentially. Python File handling
allows random access of data & built-in functions using tell( ) and seek( ) 18
Learning Objective : To interface Python code to Data Files
Access the contents of file randomly – seek() and tell()
To access the contents of file randomly – tell( ) and seek( ) methods are used.
1. tell() method returns an integer giving the current position of file pointer.
It's syntax is fileobject.tell( ) Eg: - f1.tell( )

When you open file in reading / writing mode, the file pointer is at 0th Byte.
When you open file in append mode, the file pointer is at last Byte.

The file pointer can be saved to a variable.

Learning Objective : To interface Python code to Data Files 19


Access the contents of file randomly – seek() and tell()
seek() method can be used to position the file handle(pointer) at particular place in the file.
seek () can be done in two ways :
1. Relative Positioning – The file pointer is set with reference to a point given by 0 , 1 or 2.
Syntax is fileobject.seek(offset, referencepoint) Eg: - f1.seek(10,0)
Offset is a number specifying number of bytes ; Reference point is a number 0 / 1 / 2.
• 0 beginning of the file (default value i.e. beginning of the file.) # by default
Board Qs
1. Distinguish between seek( )
• 1 current position of file and tell ( )
2. What does the tell() do?
• 2 end of file (to move the file pointer to the end of the file.) 3. What does the seek()
Eg: - f1.seek(10,0) # Move 10 bytes from the beginning of the File function do?

f1.seek(-10,2) # Move backwards by 10 bytes from the end of the File


2. Absolute Referencing – The file pointer is set with reference to a start of file.
Eg: - f1.seek(20) # Move 20 bytes from the beginning of the File
Learning Objective : To interface Python code to Data Files 20
ACCESSING DIRECTORIES
Absolute Path v/s Relative Path

Learning Objective : To interface Python code to Data Files 21


22

Absolute Path
• Absolute path is the full address of any file or folder from the Drive (Root Folder)
• Format : Drive_Name:\Folder\Folder…\filename
• Eg: - C:\Users\Jihan Shareen\Documents
• To get the Absolute path
• Right Click Properties Location.

Learning Objective : To interface Python code to Data Files


23

• Use double backslash(\\) in place of single backslash


because in Python ‘\’ is used for escape character.
(C:\Users\Document\text1.txt can cause an error )
The file name should be given as
f1=open(“C:\\Users\\Document\\text1.txt”,“r”)

OR

• Use “r” before the path making the string as raw string
i.e. no special meaning attached to any character as
f1=open(r“C:\Users\Document\text1.txt”,“r”)

Learning Objective : To interface Python code to Data Files


24

Relative Path
• Relative paths are relative to current working directory.
• To use Relative path special symbols are:
• Single Dot ( . ) : single dot ( . ) refers to current folder.
• Double Dot ( .. ) : double dot ( .. ) refers to parent folder
• Backslash ( \ ) : first backslash before (.) and double dot( .. ) refers to ROOT
folder.

Learning Objective : To interface Python code to Data Files


Root folder 25
C:\

PROJECT SALES ACCOUNTS

PROJ_1 CL DAT PROJ_2 MONTHLY YEARLY CASH ACT BANK ACT HISTORY

MAIN PRG ONE CPP JAN SAL YR1 SAL CASH ACT

REPORT
ONE BAK FEB SAL YR2 SAL BANK ACT
PRG

TWO CPP MAR SAL BACKUP

THREE CPP

∙ Absolute Path of Directory BACKUP is C:\SALES\YEARLY\BACKUP


∙ Assume current working directory is PROJ 2. The Relative Path of
i. TWO.CPP will be .\TWO.CPP (. Current directory i.e PROJ_2\TWO.CPP )
ii. CL DAT will be ..\CL.DAT (.. Parent Directory i.e PROJECT\CL.DAT)
iii. REPORT.PRG will be ..\PROJ1\REPORT.PRG (i.e PROJECT\PROJ_1\REPORT.PRG)

Learning Objective : To interface Python code to Data Files

You might also like