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

Text Files

Uploaded by

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

Text Files

Uploaded by

navaneethnrd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

FILE HANDLING

Part-1 : TEXT FILES


File
A file is a named location on a secondary storage media where data is permanently stored
for later access.
Types of Files
1.Text Files :
• Text file consists of human readable characters (alphabets, numbers and special
characters) which can be opened by any text editor. It stores information in ASCII
or Unicode characters.
• Each line of text is terminated with a special character known as EOL (End of
Line) (by default it is \n)
• Text files are having extension .txt
• Text file is the default mode of file.
File handling in Python enables us to create , update, read and delete the files stored on
the file system through our Python program. The following operations can be performed
on a file.

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.

2. using with statement


Syntax:
with open (<filename> , <filemode>) as <filehandle> :
<file manipulation statements>
Eg:
with open (‘output.txt’,’w’ ) as F:
F.write(“Welcome to Python files”)
Advantage:
• It will automatically close the file after the block of code.

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.

‘a’ *Opens the file in append mode ie, write mode


* If the file already exists , the data in the file is retained, the
new data being written will be appended to the end.
*If the file does not exist, then a new file will be created.
*File pointer is placed in the end of the file.
‘r+’ or ‘+r’ *Opens the file in both read and write mode
*File pointer is placed in the beginning of the file.
‘w+’ or ‘+w’ *Opens the file in both read and write mode
*File pointer is placed in the beginning of the file.
‘a+’ or ‘+a’ *Opens the file in both append and read mode
*File pointer is placed at the end of the file.
Example
F=open(“notes.txt”) notes.txt is a text file.It opens the file
or “notes.txt” in read mode and attaches it
F=open(“notes.txt”,”r”) to file object F.
(Python will look for notes.txt file in
current working directory. If it is not
available in the working directory it will
raise FileNotFoundError)
F1=open(“E:\\main\\result.txt”) (Python will look for this file in E:\main
folder)
(The double slashes indicate escape
sequence for slash)
or
F1=open(r”E:\main\result.txt”)

(The prefix r in front of a string makes it


raw string that means there is no special
meaning attached to any character)
F=open(“notes.txt”,”r+”) notes.txt is a text file and is opened in
read and write mode.

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)

Writing a single line string in a text file


def WRITE( ):
F=open(“test1.txt” , “w”)
F.write(“This is my first program on file handling”)
F.close( )

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( )

II.APPENDING DATA TO A FILE


• Appending means to add the data at the end of file using ‘a’ mode
• If file dosen’t exists, it will create the new file.
• If file exists, it will append the data at the end of a file

III. READING DATA FROM FILES


Python provides mainly 3 types of read functions to read from a datafile.
Note:
• You may or may not specify the ‘r’ mode as the file is by default opened in read
mode.
• If the file doesn’t exist then the file not found error occurs.
• When the file is opened in ‘r’ mode , then the file pointer moves to the beginning of
the file.
• read( ) , readline( ) and readlines( ) functions are used to read from the text file.

read( ) <file_object>.read([n]) *Reads at most n bytes


*If n is not specified , reads
the entire file.
Ms Maya Giby
PGT Computer Sc
*Returns the read bytes in
the form of a string.
readline( ) <file_object>.readline([n]) *Reads a line of input.
*If n is specified it reads at
most n bytes.
*It returns the read bytes in
the form of a string ending
with line character.
*It returns a blank string if no
more bytes are left for
reading in the file.
readlines( ) <file_object>.readlines( ) *Reads all the lines of a text
file and returns in the form
of a list.

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( )

Eg:Reading the entire content of file test1.txt

def READ( ): OUTPUT


F=open("test1.txt" ) PYTHON PROGRAMMING
str1=F.read( ) FILE HANDLING
print(str1) TEXT FILES
F.close( )

READ( )
Ms Maya Giby
PGT Computer Sc
2. readline( )
Eg:Reading the first 3 lines of file test1.txt

def READ( ): OUTPUT


F=open("test1.txt" ) PYTHON PROGRAMMING
str1=F.readline( )
print(str1) FILE HANDLING
str2=F.readline( )
print(str2) TEXT FILES
str3=F.readline( )
print(str3)
F.close( )

READ( )

def READ( ): OUTPUT


F=open("test1.txt" ) PYTHON PROGRAMMING
str1=F.readline( ) FILE HANDLING
print(str1, end ='') TEXT FILES
str2=F.readline( )
print(str2, end ='')
str3=F.readline( )
print(str3, end ='')
F.close( )

READ( )

Eg: Reading test1.txt file line by line


def READ( ): OUTPUT
F=open("test1.txt") PYTHON PROGRAMMING
str1=" " FILE HANDLING
while str1: TEXT FILES
str1=F.readline( )
print(str1, end ='')
F.close( )

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.

RANDOM ACCESS OF DATA IN FILES


seek( )
This method is used to position the file object at a particular position in a file.
Syntax:
<file object>.seek(offset [ , reference point])

offset – No of bytes by which the file object is to be moved.


reference point - it indicates the starting position of the file object.It can take 3 values
0 sets the reference point at the beginning of the file, which is by default
1 sets the reference point at the current file position.
2 sets the reference point at the end of file
tell( )
This method returns an integer that specifies the current position of the file object in the
file .The position so specified is the byte position from the beginning of the file till the
current position of the file object.
Syntax:
<file object>.tell( )

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

You might also like