Python Prog Unit-4 Notes by Kamal Kant Tripathi
Python Prog Unit-4 Notes by Kamal Kant Tripathi
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.
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
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.
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.
1. Open a file
2. Read or write (perform operation)
3. Close the 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)
The following table shows different access modes we can use while
opening a file in Python.
Mode Description
It opens the file to read and write both. The file pointer
r+
exists at the beginning.
wb+ It opens the file to write and read both in binary format
Read File
1. read() method: This method reads the whole file at a time. This
Example:
print (file.read())
Output:
Hello world
GeeksforGeeks
123 456
readline()?
Python readline() method will return a line from the file when called.
Ex:
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:
example1 = file.readlines()
print(example1).t)xt", "r")
Type of Writing Mode in File:
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 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.close()
# Output:
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
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
Example
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
Example:
q.write a python program to read a file line by line and store into a
variable.(2019-2020)
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')
file1.writelines(L)
file1.writelines(L1)
# Closing file
file1.close()
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])
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')