Session 12, Ch13-File Handling
Session 12, Ch13-File Handling
Mode Description
r Opens a file for reading
w Opens a new file for writing. I a file already exists, its contents are
destroyed
a Opens a file for appending data from the end of the file
wb Opens a file for writing binary data
rb Opens a file for reading binary data
Opening a file
File object=open(File_Name, [Access_Mode], [Buffering])
Example
F1=open("Demo.txt", "r") #Open File from Current Directory
F1=open(“c:\Demo.txt", "r") #Open File located in C:
Mode Description
r Opens a file for reading
w Opens a new file for writing. I a file already exists, its contents are
destroyed
a Opens a file for appending data from the end of the file
wb Opens a file for writing binary data
rb Opens a file for reading binary data
Writing Text to a File
File object=open(File_Name, [Access_Mode], [Buffering])
Function Meaning
write (str s) Writes strings to file
Writing Text to a File
Ex. Write a program to write the sentences given below into the file Demo1.txt
obj1=open("Demo1.txt", "w")
obj1.write("Hello, How are You? \n")
obj1.write("Welcome to the chapter File Handling. \n")
obj1.write("Enjoy the session. \n")
Closing a File
When we have finished or writing from a file, we
need to properly close it. Since an open file
consumes system resources (depending on the mode
of the file), closing it will free resources tied
to it. This is done using close() method.
Fileobject.close()
fp1=open("Demo1.txt", 'r')
fp1.close()
Writing Numbers to a File
The write() method expects a string as an argument. Therefore,
if we want to write other data types, such as integers or
floating point numbers then the numbers must be first
converted into strings before writing them to an output file.
In order to read the numbers correctly, we need to separate
them using special characters, such as “ “ (space) or ‘\n’
(new line).
Function Meaning
str read( ) Returns all the data from a file and return one complete string
str readline( ) Returns the next line of file as a string
list readlines( ) Returns a list containing all the lines in a file
str read([int number]) Returns a specified number of characters from a file. If the argument
is omitted, then the entire content of the file is read.
Reading Text from a File
fp=open("ReadDemo1.txt", "r")
text=fp.read()
print(text)
Output:
I
Love
Python
Programming
Language
Reading Text from a File
Alternative way to read a file using loop
fp=open("ReadDemo1.txt", "r")
for x in fp:
print(x)
File Pointer: tell( ) and seek( )