Lec 17. File Handling
Lec 17. File Handling
(IT1001)
Lecture - 17
• Reading file
• Writing file
• File Positioning
What Is a Text File ?
• File is a named location on disk to store related information. It is used
to permanently store data in a non-volatile memory.
• Python provides several functions for performing the above file operations
Opening Text Files: open() function
• All files must first be opened before they can be used. In Python, when a file is
opened, a file object is created that provides methods for accessing the file.
• The open() is a key function for working with files. This function takes two
parameters; filename, and mode.
• Note: The value of access_mode depends on the which you want to perform with
file. There are different modes while opening a file.
File Access Modes
S. No. Mode Value Mode Name Description
1. "r" Read Default value. Opens a file for reading, error if the file
does not exist.
2. "w" Write Opens a file for writing, creates the file if it does not exist
3. "a" Append Opens a file for appending, creates the file if it does not
exist
4. "x" Create Creates the specified file, returns an error if the file exists
5. “r+" Read + write For both reading and writing
6. "t" Text Default value. Text mode
Example:
f = open("foo.txt", "wb")
Output:
Name of the file: foo.txt
print ("Name of the file: ", f.name)
Closed or not : False
print ("Closed or not : ", f.closed)
Opening mode : wb
print ("Opening mode : ", f.mode)
File Reading: Example
#Reading Myfile.txt Myfile.txt
• The open() function returns a file object, which has a read() method for reading the content of
the file.
• By default the read() method returns the whole text, but you can also specify how many
characters you want to return.
• It is a good practice to always close the file when you are done with it.
Note: It is enough to specify only the name of the file while opening a file for reading.
File Reading: Another Example
• We can also split lines using split() function. This splits the variable when space is
encountered.
• You can also split using any characters as we wish.
Output:
print(File_ptr.readline()) print(File_ptr.readline())
File_ptr.close() print(File_ptr.readline())
File_ptr.close()
Output:
Output:
Hello! Welcome to Myfile.txt
Hello! Welcome to Myfile.txt
Reading the file is very easy.
Output:
• Creating new file: To create a new file in Python, use the open() method, with one of
the following parameters.
• "x" - Create - will create a file, returns an error if the file exist
• "a" - Append - will create a file if the specified file does not exist
• "w" - Write - will create a file if the specified file does not exist
• You can use the os.mkdir() method of the os module to create directories in the
current directory.
# Create a directory "test"
import os
os.mkdir("test")
Change and Get Current Directory
• You can use the os.chdir() method to change the current directory.
import os
• tell() method: Tells you the current position of the file pointer within the file.
• In other words, the next read or write will occur at that many bytes from the
beginning of the file.
• seek(offset, from) method: Changes the current file position of file pointer.
• The offset argument indicates the number of bytes/characters to be moved.
• The from argument specifies the reference position from where the
bytes/characters are to be moved. It can be 0: Beginning, 1: Current, and 2: End
Position.
File Positions: Example
# Open a file. Assume file is already created
fp = open(“Test.txt", "r+")
str = fp.read(10) # Contents of Test.txt:
print ("Read String is : ", str)
Python is a Programming
Language.
# Check current position
position = fp.tell()
print ("Current file position : ", position)
Number of paragraph
MCQs
1. Indicate which of the following reasons an IOError 3. Only files that are written to need to be
(exception) may occur when opening a file. opened first.
a) Misspelled file name a) True b) False
b) Unmatched uppercase and lowercase letters 4. Which one of the following is true?
c) File not found in directory searched a) There is more chance of an I/O error
when opening a fi le for reading.
2. Which one of the following is true? b) There is more chance of an I/O error
when opening a fi le for writing.
a) When calling the built-in open function, a
second argument of 'r’ or 'w’ must always be 5. The readline() method reads every character
given from a text fi le up to and including the next
b) When calling the built-in open function, a newline character '\n’.
second argument of 'r’ must always be given a) True b) False
when opening a fi le for reading.
6. It is especially important to close a file that is
c) When calling the built-in open function, a open for writing.
second argument of 'w’ must always be given a) True b) False
when opening a fi le for writing.
MCQs: Answers
1. Indicate which of the following reasons an IOError 3. Only files that are written to need to be
(exception) may occur when opening a file. opened first.
a) Misspelled file name a) True b) False
b) Unmatched uppercase and lowercase letters 4. Which one of the following is true?
c) File not found in directory searched a) There is more chance of an I/O error
when opening a fi le for reading.
2. Which one of the following is true? b) There is more chance of an I/O error
when opening a fi le for writing.
a) When calling the built-in open function, a
second argument of 'r’ or 'w’ must always be 5. The readline() method reads every character
given from a text fi le up to and including the next
b) When calling the built-in open function, a newline character '\n’.
second argument of 'r’ must always be given a) True b) False
when opening a fi le for reading.
6. It is especially important to close a file that is
c) When calling the built-in open function, a open for writing.
second argument of 'w’ must always be a) True b) False
given when opening a fi le for writing.