Text File Notes
Text File Notes
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.
• 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
Eg : f1 = open(“Subjects.txt”, “r”)
Eg : f1.close( )
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 '.’
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'.
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.
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.
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”)
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.
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
THREE CPP