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

Python Prog Unit-4 Notes by Kamal Kant Tripathi

The document provides an overview of file handling in Python, explaining the types of files (text and binary) and the basic operations such as creating, opening, reading, writing, renaming, and deleting files. It details the use of built-in functions like open(), close(), read(), write(), and the importance of file access modes. Additionally, it covers exception handling during file operations and includes examples for practical understanding.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Python Prog Unit-4 Notes by Kamal Kant Tripathi

The document provides an overview of file handling in Python, explaining the types of files (text and binary) and the basic operations such as creating, opening, reading, writing, renaming, and deleting files. It details the use of built-in functions like open(), close(), read(), write(), and the importance of file access modes. Additionally, it covers exception handling during file operations and includes examples for practical understanding.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Python Programming

UNIT-4
Notes By: Kamal Kant Tripathi
Asst.Prof. in VCM ,Kanpur

What is a File?
A file is a resource to store data. As part of the programming
requirement, we may have to store our data permanently for future
purpose. For this requirement we should go for files. Files are very
common permanent storage areas to store our data.

A file is some information or data which stays in the computer storage


devices. You already know about different kinds of file , like your music
files, video files, text files. Python gives you easy ways to manipulate
these files.

Generally we divide files in two categories, text file and binary file.
Text files are simple text where as the binary files contain binary data
which is only readable by computer..
Types of File

Text File: Text file usually we use to store character data. For example,
test.txt

Binary File: The binary files are used to store binary data such as
images, video files, audio files, etc

What Is a Python File IO?(2019-2020)


A file is a resource that allows the user to store a piece of data or
information in the non-volatile memory of a computer. It is stored in the
form of bytes, and Python treats it as either text or binary.

The Python file IO is either a text file or a binary file in which each line
ends with a special character to indicate the end of the line. In Python
programming language,

the operations on the file are performed in the following sequence: first,
you need to open a file, then perform the required function, and close the
file. Almost all file handling processes involve opening and closing files.
However, the function may change from time to time.

How Does Python handle File IO?


The Python programming language handles file IO as either text or
binary. It provides built-in functions (open() and close()) to open and
close specific files respectively.
The open() function opens a file, also known as a handle, that can be
used according to the user’s needs, i.e., read, write, edit, etc. It allows
the user to provide the file mode in which a user wants to open the file.

For example, if a user wants to open a file in write mode, “w” needs to
be provided, and if a user wants to open a file in read mode, “r” needs to
be provided.

Common operation of FILE:


 Create File in Python: You'll learn to create a file in the current
directory or a specified directory. Also, create a file with a date and
time as its name. Finally, create a file with permissions.
 Open a File in Python: You'll learn to open a file using both
relative and absolute paths. Different file access modes for opening
a file read and write mode.
 Read File in Python: You'll learn to read both text and binary files
using Python. The different modes for reading the file. All methods
for reading a text file such as read(), readline(), and readlines()
 Write to File Python: You'll learn to write/append content into text
and binary files using Python. All methods for writing a text to file,
such as write(), writelines().
 File Seek(): Move File Pointer Position: You'll learn to use
the seek() function to move the position of a file pointer while
reading or writing a file.
 Rename Files in Python: You'll learn to rename a single file or
multiple files. Renaming files that match a pattern. Rename all the
files in a folder.
 Delete Files and Directories in Python: You'll learn to delete files
using the os module and pathlib module. Remove files that match a
pattern (wildcard). Delete a directory and all files from it
Hence, in Python, a file operation takes place in the following order:

1. Open a file
2. Read or write (perform operation)
3. Close the file

Working of open() Function in Python


Before performing any operation on the file like reading or writing,
first, we have to open that file.

for this, we should use Python’s inbuilt function open() but at the time
of opening, we have to specify the mode, which represents the purpose
of the opening file.

f = open(filename, mode)

f = Name of file pointer

filename= name of file which we want to open


Mode= in which mode we want to open the File

File Access Modes(2022-2023)

The following table shows different access modes we can use while
opening a file in Python.
Mode Description

It opens an existing file to read-only mode. The file


r
pointer exists at the beginning.

It opens the file to read-only in binary format. The file


rb
pointer exists at the beginning.

It opens the file to read and write both. The file pointer
r+
exists at the beginning.

It opens the file to read and write both in binary format.


rb+
The file pointer exists at the beginning of the file.

It opens the file to write only. It overwrites the file if

w previously exists or creates a new one if no file exists

with the same name.

It opens the file to write only in binary format. It

wb overwrites the file if it exists previously or creates a new

one if no file exists.


Mode Description

It opens the file to write and read data. It will override


w+
existing data.

wb+ It opens the file to write and read both in binary format

It opens the file in the append mode. It will not override

a existing data. It creates a new file if no file exists with

the same name.

ab It opens the file in the append mode in binary format.

a+ It opens a file to append and read both.

ab+ It opens a file to append and read both in binary format.

Read File

1. read() method: This method reads the whole file at a time. This

method returns \n for the new line.

Example:

file = open("geeks.txt", "r")

print (file.read())
Output:

Hello world
GeeksforGeeks
123 456

readline()?
Python readline() method will return a line from the file when called.

Python readline() syntax


1 file = open("filename.txt", "r")
2 file.readline()

Ex:

file = open("example.txt", "r")

example1 = file.readline()

print(example1)
readlines()
readlines() method will return all the lines in a file in the format of
a list where each element is a line in the file.

readlines() Syntax

1 file = open("filename.txt","r")
2 file.readlines()

Ex:

file = open("example.txt", "r")

example1 = file.readlines()
print(example1).t)xt", "r")
Type of Writing Mode in File:

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

Append mode
"Appending" means adding something to the end of another thing.
The "a" mode allows you to open a file to append some content to it

Example:

f = open("d:\kkkkk.txt", "a")

f.write("\n New Line")

f.write("\n kamal")

f = open("d:\kkkkk.txt", "r")

print(f.read())

print()

f.close()
How Do I Create a New text File in Python? (2022-2023)
Here’s a simple example using the ‘w’ method instead:

Example:

file = open('myfile.txt', 'w')

file.close()

# Output:

# Creates a new file named 'myfile.txt' in the current directory

Creating a File using the write() Function

the write() function is used to write in a file. The close() command


terminates all the resources in use and frees the system of this particular
program.

There are two ways to write in a file.


write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)

writelines() : For a list of string elements, each string is inserted in the


text file. Used to insert multiple strings at a single time.
File_object.writelines(L) for L = [str1, str2, str3]
Note: ‘\n’ is treated as a special character of two bytes.
Python3
# Opening a file

file1 = open('myfile.txt', 'w')


L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
s = "Hello\n"

# Writing a string to file


file1.write(s)

# Writing multiple strings


# at a time
file1.writelines(L)
file1.close()

# Checking if the data is written to file or not


file1 = open('myfile.txt', 'r')
print(file1.read())
file1.close()

Move File Pointer

The seek() method is used to change or move the file's handle


position to the specified location. The cursor defines where the data has
to be read or written in the file.

The position (index) of the first character in files is zero, just like
the string index.
Example

f = open("sample.txt", "r")
# move to 11 character
f.seek(11)
# read from 11th character
print(f.read())
Output:

PYnative.com

This is a sample.txt

Line

Line 4

The tell() Method

The tell() method to return the current position of the file


pointer from the beginning of the file.

tell() Example

f = open("sample.txt", "r")
# read first line
f.readline()
# get current position of file handle
print(f.tell())
The close() method :

You should always close your files, in some cases, due to buffering,
changes made to a file may not show until you close the file.

Syntax

file.close()
Delete a File

To delete a file, you must import the OS module, and run


its os.remove() function:

Example

Remove the file "demofile.txt":


import os
os.remove("demofile.txt")
Python Rename File
is a method used to rename a file or a directory in Python programming.
The Python rename() file method can be declared by passing two
arguments named src (Source) and dst (Destination).

Syntax
This is the syntax for os.rename() method

os.rename(src, dst)

Parameters
src: Source is the name of the file or directory. It should must already
exist.

dst: Destination is the new name of the file or directory you want to
change.

Example:

import os
os.rename('guru99.txt','career.guru99.txt')

Q.How can you create Python file that can be imported as a library as
well as run as a standalone script? .(2020-21)
Creating and Importing a module

A module is simply a Python file with a .py extension that can be


imported inside another Python program. The name of the Python file
becomes the module name.
The module contains definitions and implementation of classes,
variables, and functions that can be used inside another program.
Example: Let’s create a simple module named GFG.
Examaple:
''' GFG.py '''
# Defining a function
def Geeks():
print("GeeksforGeeks")
# Defining a variable
location = "Noida"
The above example shows the creation of a simple module named
GFG as the name of the above Python file is GFG.py. When this code
is executed it does nothing because the function created is not invoked.
To use the above created module, create a new Python file in the same
directory and import GFG module using the import statement.

Example:

# Python program to demonstrate modules


import GFG

# Use the function created


GFG.Geeks()
# Print the variable declared
print(GFG.location)
Output:
GeeksforGeeks
Noida

q.write a python program to read a file line by line and store into a
variable.(2019-2020)

file = open("example.txt", "r")

example1 = file.readlines()

print(example1).
q.Write python program to the number of letters and digits in given input
sring into a file project.(2022-23)
file1 = open('myfile.txt', 'w')

L = ["a,", "b,", "c\n"]

L1 = ["1,", "2,", "3"]

# Writing a string to file

file1.writelines(L)

# Writing multiple strings


# at a time

file1.writelines(L1)

# Closing file

file1.close()

# Checking if the data is

# written to file or not

file1 = open('myfile.txt', 'r')

print(file1.read())

file1.close()

q. There is a file named Input.Txt. Enter some positive numbers into the
file named Input.Txt. Read the contents of the file and if it is an odd
number write it to ODD.TXT and if the number is even, write it to
EVEN.TXT.(2021-22)
Solution:
file = open("d:\kk.txt","r")
for i in file:
if i.strip:
num = int(i)
if (num % 2 == 0):
even = open("d:\even.txt","a")
even.write(str(num))
even.write("\n")
else:
odd = open("d:\odd.txt","a")
odd.write(str(num))
odd.write("\n")
Python strip() function is used to remove extra whitespaces and
specified characters from the start and from the end of the string.
Syntax:

string.strip([characters])

Exception Handling in Files

If an exception occurs when we are performing some operation with the file,
the code exits without closing the file. A safer way is to use a try...finally block.
Let's see an example,

try:
file1 = open("test.txt", "r")
read_content = file1.read()
print(read_content)

finally:
# close the file
file1.close()

Here, we have closed the file in the finally block as finally always executes,
and the file will be closed even if an exception occurs.
Copy Files

There are several ways to cop files in Python. The shutil.copy() method is used to
copy the source file's content to the destination file.

Example

import shutil

src_path = r"E:\demos\files\report\profit.txt"
dst_path = r"E:\demos\files\account\profit.txt"
shutil.copy(src_path, dst_path)
print('Copied')

You might also like