0% found this document useful (0 votes)
37 views29 pages

Lec 17. File Handling

The document discusses file handling in Python including opening and closing files, reading from files, writing to files, and deleting files and directories. It describes text files and binary files, different file access modes, and using functions like open(), read(), write(), readline() to perform file operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views29 pages

Lec 17. File Handling

The document discusses file handling in Python including opening and closing files, reading from files, writing to files, and deleting files and directories. It describes text files and binary files, different file access modes, and using functions like open(), read(), write(), readline() to perform file operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Introduction to Programming in Python

(IT1001)

Lecture - 17

File Handling in Python

Dr. Vijaypal Singh Rathor (Course Instructor)


Assistant Professor, Department of CSE
(Email: [email protected])
Lecture Contents
• File Handling:
• File Opening and Creating and Closing

• Reading file

• Writing file

• Deleting file and Directory

• 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.

• A text file is a file containing characters, structured as lines of text.


• In addition, text files also contain the nonprinting newline character,
\n, to denote the end of each text line.

• A binary file is a file that is formatted in a way that only a computer


program can read.
Note: we will be going to work mainly with txt files. Python supports file
handling in very easy and short manner compared to other languages.
File Operations
• Python allows the user to handle the file by performing following operations on
it:

• Opening or creating a file


• Reading a file
• Writing into a file
• Appending into a files
• Close the file

• 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.

• Syntax: File_pointer = open(<file_name/path>, <access_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

7. "b" Binary Binary mode (e.g. images)


File Access Modes: Description
S. N. Mode Description
1. “r” Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the
default mode.
2. “rb” Opens a file for reading only in binary format. The file pointer is placed at the beginning of
the file. This is the default mode.
3. “r+” Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
4. “w” Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist,
creates a new file for writing.
5. “w+” Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the
file does not exist, creates a new file for reading and writing.
6. “a” Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the
file is in the append mode. If the file does not exist, it creates a new file for writing.
7. “a+” Opens a file for both appending and reading. The file pointer is at the end of the file if the file
exists. The file opens in the append mode. If the file does not exist, it creates a new file for
reading and writing.
The file Object Attributes
• Once a file is opened and you have one file object, you can get various
information related to that file.

S. No. Attribute Description


1 file.closed Returns true if file is closed, false otherwise.

2 file.mode Returns access mode with which file was opened.

3 file.name Returns name of the file.


The file Object Attributes: Example
• Once a file is opened and you have one file object, you can get various
information related to that file.

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

File_ptr = open(“Myfile.txt", "r") Hello! Welcome to Myfile.txt


print(File_ptr.read()) Reading the file is very easy.
print(File_ptr.read(5)) Now you can read a file from your hard disk
Good Luck!
File_ptr.close()

• 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.

# Python code to illustrate split() function


# Contents of Testfile.txt:
with open(“Testfile.txt", "r") as file:
data = file.readlines() Hello this test file.
for line in data: It is splitting the lines.
word = line.split()
print(word)

Output:

['Hello', 'this', 'test', 'file.’]


['It', 'is', 'splitting', 'the', 'lines.']
File Reading: Example
#Reading Myfile.txt #Reading Myfile.txt

File_ptr = open("Myfile.txt", "r") File_ptr = open(“Myfile.txt", "r")

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.

• You can return one line by using the readline() method.


• By calling readline() two times, you can read the first two lines.

How the file having large number of lines can be read ?


File Reading: Example
• By looping through the lines of the file, you can read the whole file, line by line.

#Reading Myfile.txt Myfile.txt


f = open(“Myfile.txt", "r")
for x in f: Hello! Welcome to Myfile.txt
print(x) Reading the file is very easy.
f. close() Now you can read a file from your hard disk
Good Luck!

Output:

Hello! Welcome to Myfile.txt


Note: The file object also provides a set
Reading the file is very easy.
of access methods to write files.
Now you can read a file from your hard disk
Good Luck!
File Writing
• There are following ways to write into a file:
• Writing to an existing file: To write to an existing file, you must add a parameter to
the open() function.
• "a" - Append - will append to the end of the file
• "w" - Write - will overwrite any existing content

• 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

• The write() method is used to write strings to a file.


Writing to an Existing File: Appending

#Example: Open the file “Myfile2.txt" and append Myfile2.txt


content to the file
Hello! Welcome to Myfile2.txt
f = open(“Myfile2.txt", "a")
This file is for testing purposes.
f.write("Now the file has more content!")
Good Luck!
f.close()

#open and read the file after the Output:


appending:
f = open(“Myfile2.txt", "r") Hello! Welcome to Myfile2.txt
print(f.read()) This file is for testing purposes.
f.close() Good Luck!Now the file has more
content!
Writing to an Existing File: Overwriting

#Example: Open the file “Myfile2.txt" and overwrite # Myfile2.txt


the content
Hello! Welcome to Myfile.txt
f = open(“Myfile2.txt", "w") This file is for testing purposes.
f.write("Woops! I have deleted the content!") Good Luck!
f.close()

#open and read the file after the appending:


f = open(“Myfile2.txt", "r") Output:
print(f.read())
f.close() Woops! I have deleted the content!
Create a New File
Result: a new empty file is created!
#Example: Create a file called "myfile3.txt"
# Myfile3.txt
f = open("myfile3.txt", "x")
f.write(“It is written in this file.”) It is written in this file.
f.close()

#open and read the file after the appending:


f = open(“Myfile3.txt", "r") Output:
print(f.read())
f.close() It is written in this file.

#Example: Create a new file if it does not exist"


# Myfile4.txt
f = open("myfile4.txt", "x")
f.write(“The contents are written using W mode.”) The contents are written using W mode.
f.close()
Writing Multiple Lines into a File
Example1: Example2:
with open(“Test.txt",'w') as fp: fp = open(“Test.txt",'w')
fp.write(“My first file\n") fp.write(“My first file\n")
fp.write("This file\n\n") fp.write("This file\n\n")
fp.write("contains three lines\n") fp.write("contains three lines\n")
fp.close() fp.close()
#Contents in Test.txt:
My first file
Note: By looping, you can write the
This file
large number of lines into the file.

contains three lines


File Deleting and Renaming
• To delete a file, you must import Example: Remove the file "demofile.txt":
the OS module, and run its import os
os.remove("demofile.txt")
os.remove() function.

Example: Check if file exists, then delete it:


• To avoid getting an error, you might import os
want to check if the file exists if os.path.exists("demofile.txt"):
before you try to delete it. os.remove("demofile.txt")
else:
print("The file does not exist")
• The rename() method takes two
arguments, the current filename Example: # Rename a file from test1.txt to
and the new filename. test2.txt
import os
os.rename( "test1.txt", "test2.txt" )
Create and Delete Folder/Directory
• To delete an entire folder, use the os.rmdir() method:

#Example: Remove the folder "myfolder":


Note: You can only
import os remove empty folders.
os.rmdir("myfolder")

# This would remove "/tmp/test" directory.


os.rmdir( "/tmp/test" )

• 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.

• The os.getcwd() method displays the current working directory.

import os

# Changing a directory to "/home/newdir"


os.chdir("/home/newdir")

# This would give location of the current directory


os.getcwd()
File Positions
• Python provides the following file positioning functions:

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

# Reposition pointer at the beginning once again


position = fp.seek(0, 0);
str = fp.read(10)
print ("Again read String is : ", str)
Output:
Read String is : Python is
# Close opend file Current file position : 10
fp.close() Again read String is : Python is
Exercise1: Copying File
• Write a program to copy contents of file myfile.txt to myfile_copy.txt
Exercise 2 Number of words

Number of character (with space)

• Write a code to read file Number of character (without space)


and give you summary of
the file.
Frequency of character

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.

You might also like