Text Files
Text Files
Opening Files
1.open( ) is used to open the file.
Syntax :
<file_objectname> = open(<file_name> , [<access_mode>])
file_objectname : It is also called file_handle.It is a reference to a file on disk. It opens
and makes it available for a number of different tasks.
file_name : (Path to a file)Name of the file enclosed in double quotes.
access_mode : File mode determines what kind of operations(such as read or write or
append) can be performed in the opened file.
Ms Maya Giby
PGT Computer Sc
• If any exception (run time error) occurs before the end of the block, the with
statement will handle it and close the file.
Text File Mode Description
‘r’ *Opens the file in read only mode
* File must exist , otherwise error is raised.
*File pointer is placed in the beginning of the file.
‘w’ *Opens the file in write only mode
* If the file already exists , all the content will be overwritten.
*If the file does not exist, then a new file will be created.
*File pointer is placed in the beginning of the file.
Closing Files
Ms Maya Giby
PGT Computer Sc
Syntax: <file_objectname>.close( )
It is used to close the file object, once we have finished working on it.This 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.
Eg: F.close( )
I .WRITING DATA INTO A TEXT FILE
1.write( )
2. writelines( )
1)write( )
• write( ) method takes a string (as parameter) and writes it in the text file.
• For storing data, with EOL character, we have to add ‘\n’ character to the end of the
string.
• For storing numeric value, we have to either convert it into string using str( ) or
write in quotes.
Syntax:
<file_object>.write(string)
WRITE( )
or
def WRITE( ):
F=open(“test1.txt” , “w”)
str=input(“Enter a line”)
F.write(str)
F.close( )
WRITE( )
Writing multiple lines of string in a text file
def WRITE( ):
F=open(“test1.txt” , “w”)
F.write(“Python Programming is fun\n”)
F.write(“Python is case sensitive language\n”)
F.write(“Python is an open source software”
F.close( )
WRITE( )
or
def WRITE( ):
F=open(“test1.txt” , “w”)
while True:
Ms Maya Giby
PGT Computer Sc
str=input(“Enter a line”)
F.write(str +’\n’)
ch =input(“More lines to enter(y/n)”)
if ch == ‘n’ or ch == ‘N’ :
break
F.close( )
WRITE( )
2.) writelines( )
• It is used to write sequence data types in a file (string, list and tuple etc.)
• ‘\n’ required for line break
• No difference between write( ) and writelines( ) if single string is passed as
parameter.
Syntax:
<file_object>.writelines(List/string/tuple)
Eg:
def WRITE( ):
F=open("test1.txt" , "w")
L=["PYTHON PROGRAMMING\n","FILE HANDLING\n","TEXT FILES"]
F.writelines(L)
F.close( )
WRITE( )
1. read( ) method
Eg:Reading 10 bytes from the text file test1.txt
def READ( ): OUTPUT
F=open("test1.txt" ) PYTHON PRO
str1=F.read(10)
print(str1)
F.close( )
READ( )
Eg:Reading 10 bytes from the text file test1.txt and then read 20 bytes from the file.
def READ( ): OUTPUT
F=open("test1.txt" ) PYTHON PRO
str1=F.read(10) GRAMMING
print(str1) FILE HANDLI
str2=F.read(20)
print(str2)
F.close( )
READ( )
READ( )
Ms Maya Giby
PGT Computer Sc
2. readline( )
Eg:Reading the first 3 lines of file test1.txt
READ( )
READ( )
READ( )
Note:
Ms Maya Giby
PGT Computer Sc
• The readline( ) function reads the leading and trailing spaces along with trailing
newline character (‘\n’) also while reading the line.
• Remove these leading and trailing white spaces using strip( )
Eg:Reading test1.txt file line by line without leading and trailing spaces
def READ( ):
F=open("test1.txt" )
str1 =" "
while str1:
str1=F.readline( )
str1=str1.strip()
print(str1)
F.close( )
READ( )
Eg:Reading the first 3 characters of each line of file
def READ( ): OUTPUT
F=open("test1.txt") PYT
str1=" " FIL
while str1: TEX
str1 = F.readline(3 )
F.readline()
print(str1)
F.close( )
READ( )
NOTE: read( ) and readline( ) read the contents from a file as a string
3. readlines( )
Reads the entire content of the file as a list of strings.
Eg: Reading the complete file in a list
def READ( ): OUTPUT
F=open("test1.txt" ) ['PYTHON PROGRAMMING\n', 'FILE
str1=F.readlines( ) HANDLING\n', 'TEXT FILES\n']
print(str1)
F.close( )
READ( )
Ms Maya Giby
PGT Computer Sc
read( ) readline( ) readlines( )
It reads the entire file It reads the first line as a It reads the entire file
content as a single string string content as a list of strings.
The number of items in the
list will be based on the
number of lines written in
the text file.
After reading the file After reading, the file After reading the file pointer
pointer goes to the end of pointer goes to first goes to the end of the file.
the file. character of the next line.
read(n) will extract n bytes readline(n) will extract n readlines(n) will read n
or reads n no. of characters bytes or reads n number of bytes which is generally
from the string characters from the string. rounded off to read the
entire line.
Eg:
def READ( ):
F=open("test1.txt")
print(F.tell( ) )
print(F.read( ))
F.seek(6)
print(F.read( ))
F.seek(4)
Ms Maya Giby
PGT Computer Sc
print(F.read( 5))
print("Current location of file pointer " ,F.tell( ))
F.close( )
READ( )
OUTPUT
0
PYTHON PROGRAMMING
FILE HANDLING
TEXT FILES
PROGRAMMING
FILE HANDLING
TEXT FILES
ON PR
Current location of file pointer 9
Ms Maya Giby
PGT Computer Sc