Printing to the Screen:
The simplest way to produce output is using the print statement where you can pass zero or more
values separated by commas.
This function converts the expressions you pass into a string and writes the result to standard
output/monitor
Ex:
print (“Hello ", “DD")
Reading Keyboard Input:
Python 2 has two built-in functions to read data from standard input, which by default comes from the
keyboard. These functions are
input() and raw_input()
In Python 3, raw_input() function is deprecated. Moreover, input() functions read data from keyboard
as string.
Ex:
x = input("Please Enter Something\n")
print(x)
print(type(x))
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
What is a file:
As the part of programming requirement, we 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.
File is a named location on disk to store related information. It is used to permanently store data in a
non-volatile memory (e.g. hard disk).
Types of Files
There are 2 types of files
1. Text Files:
Usually we can use text files to store character data
Ex: abc.txt
2. Binary Files:
Usually we can use binary files to store binary data like images,video files, audio files etc...
2 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
3 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
4 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
5 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
When we want to read from or write to a file we need to open it first. When we are done, it needs to
be closed, so that resources that are tied with the file are freed.
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
Opening a File:
Before performing any operation (like read or write) on the file, first we have to open that file.
For this we should use Python's inbuilt function open()
But at the time of open, we have to specify mode,which represents the purpose of opening file.
Syntax:
f = open(filename, mode)
The allowed modes in Python are
r -> open an existing file for read operation. The file pointer is positioned at the beginning of the
file. If the specified file does not exist then we will get FileNotFoundError.
This is default mode.
w -> Open an existing file for write operation. If the file already contains some data then it will be
overridden. If the specified file is not already available then this mode will create that file.
6 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
a -> open an existing file for append operation. It won't override existing data. If the specified file is
not already available then this mode will create a new file.
r+ -> To read and write data into the file. The previous data in the file will not be deleted.
The file pointer is placed at the beginning of the file.
w+ -> To write and read data. It will override existing data.
a+ -> To append and read data from the file. It will not override existing data.
x -> To open a file in exclusive creation mode for write operation. If the file already exists then we
will get FileExistsError.
Note:
All the above modes are applicable for text files.
If the above modes suffixed with 'b' then these represents for binary files.
Ex:
rb,wb,ab,r+b,w+b,a+b,xb
f = open("abc.txt","w")
We are opening abc.txt file for writing data.
How to open a file?
Python has a built-in function open() to open a file. This function returns a file object, also called a
handle, as it is used to read or modify the file accordingly.
f = open("test.txt") # open file in current directory
f = open(“E:/Raj.txt") # specifying full path
We can specify the mode while opening a file. In mode, we specify whether we want to read 'r', write
'w' or append 'a' to the file. We also specify if we want to open the file in text mode or binary mode.
7 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
The default is reading in text mode. In this mode, we get strings when reading from the file.
On the other hand, binary mode returns bytes and this is the mode to be used when dealing with non-
text files like image or exe files.
Closing a File:
After completing our operations on the file,it is highly recommended to close the file.
For this we have to use close() function.
f.close()
8 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
The close() Method:
The close() method of a file object flushes any unwritten information and closes the file object, after
which no more writing can be done.
Python automatically closes a file when the reference object of a file is reassigned to another file. It is
a good practice to use the close() method to close a file.
Syntax:
fileObject.close();
Ex:
9 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
This method is not entirely safe. 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.
Ex:
10 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Syntax:
try:
stream = open('animals.txt')
# your code goes here
stream.close()
except Exception as e:
print('An error occurred: ', e)
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
try:
stream = open('animalsssd.txt')
# your code goes here
stream.close()
except Exception as e:
print('An error occurred: ', e)
Various properties of File Object:
Once we opened a file and we got file object , we can get various details related to that file by using
its properties.
name -> Name of opened file
mode -> Mode in which the file is opened
closed -> Returns boolean value indicates that file is closed or not
readable()-> Returns boolean value indicates that whether file is readable or not
writable()-> Returns boolean value indicates that whether file is writable or not.
11 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
[FileDemo1.py]
f=open("abc.txt",'w')
print("File Name: ",f.name)
print("File Mode: ",f.mode)
print("Is File Readable: ",f.readable())
print("Is File Writable: ",f.writable())
print("Is File Closed : ",f.closed)
f.close()
print("Is File Closed : ",f.closed)
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Writing data to text files:
We can write character data to the text files by using the following 2 methods.
Ex:
write(str)
writelines(list of lines)
[FileDemo2.py]
f=open(“MyFile.txt",'w')
f.write(“DD\n")
f.write(“Singh\n")
f.write(“Python Trainer\n")
print("Data written to the file successfully")
f.close()
12 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Note:
In the above program, data present in the file will be overridden every time if we run the program.
Instead of overriding if we want append operation then we should open the file as follows.
Ex:
f = open(“MyFile.txt","a")
Ex:
f=open(“MyFile.txt",'w')
list=[“DD\n",“Dev\n",“Lata\n",“Shweta"]
f.writelines(list)
print("List of lines written to the file successfully")
f.close()
Note:
while writing data by using write() methods, compulsory we have to provide line seperator(\
n),otherwise total data should be written to a single line.
write() vs writelines():
write(arg) expects a string as argument and writes it to the file. If you provide a
list of strings, it will raise an exception.
writelines(arg) expects an iterable as argument (an iterable object can be a tuple,
a list, or an iterator in the most general sense).
Each item contained in the iterator is expected to be a string. A tuple of strings is
what you provided, so things worked.
13 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
# write() vs writelines() function
first_string = "Hello"
second_string = "World!"
third_string = "I am "
fourth_string = "learning"
fifth_string = "Python"
full_string = [first_string, second_string, third_string, fourth_string, fifth_string]
new_file = open("demoFile.txt", 'w')
new_file.write(full_string)
#new_file.writelines(full_string)
new_file.close()
Reading Character Data from text files:
We can read character data from text file by using the following read methods.
read()-> To read total data from the file
read(n) -> To read 'n' characters from the file
14 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
readline()-> To read only one line
readlines()-> To read all lines into a list
[RDemo1.py]
read() -> To read total data from the file
Ex-1: To read total data from the file
f=open(“e:/Raj.txt",'r')
data=f.read()
print(data)
f.close()
Ex:
try:
stream = open('animals.txt')
print(stream.read())
stream.close()
except Exception as e:
print('An error occurred: ', e)
[RDemo2.py]
Ex-2:
To read only first 10 characters:
f=open(“e:/Raj.txt",'r')
15 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
data=f.read(10)
print(data)
f.close()
Ex:
try:
stream = open('animals.txt')
print(stream.read(10))
print(stream.read(10))
stream.close()
except Exception as e:
print('An error occurred: ', e)
Ex:
try:
stream = open('animals.txt')
print(stream.read(10000))
print(stream.read(1))
stream.close()
except Exception as e:
print('An error occurred: ', e)
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
16 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
try:
stream = open('animals.txt')
character = stream.read(1)
while character != '':
print(character, end='-')
character = stream.read(1)
stream.close()
except Exception as e:
print('An error occurred: ', e)
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ex:
try:
stream = open('animals.txt')
counter = 0
character = stream.read(1)
while character != '':
counter += 1
print(character, end='-')
character = stream.read(1)
stream.close()
print('\nNumber of characters:', counter)
17 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
except Exception as e:
print('An error occurred: ', e)
[RDemo3.py]
Ex-3: To read data line by line:
f=open(“e:/Raj.txt",'r')
line1=f.readline()
print(line1,end='')
line2=f.readline()
print(line2,end='')
line3=f.readline()
print(line3,end='')
f.close()
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ex:
try:
stream = open('animals.txt')
counter = 0
line = stream.readline()
while line != '':
counter += 1
18 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
print(line, end='-')
line = stream.readline()
stream.close()
print('\nNumber of lines:', counter)
except Exception as e:
print('An error occurred: ', e)
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
How to read a File line-by-line using for loop?
Ex:
myfile = open("test.txt", "r")
for line in myfile:
print(line)
myfile.close()
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
How to read a File line-by-line using a while loop?
Ex:
myfile = open("test.txt", "r")
while myfile:
19 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
line = myfile.readline()
print(line)
if line == "":
break
myfile.close()
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
[RDemo4.py]
Ex 4:- To read all lines into list:
f=open(“e:/Raj.txt",'r')
lines=f.readlines()
for line in lines:
print(line,end='')
f.close()
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ex:
try:
stream = open('animals.txt')
lines = stream.readlines()
20 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
print('Content of the lines var:', lines)
print('Number of lines in the file:', len(lines))
for line in lines:
print(line, end='')
stream.close()
except Exception as e:
print('An error occurred: ', e)
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
try:
stream = open('animals.txt')
lines = stream.readlines(2)
while len(lines) != 0:
for line in lines:
print(line, sep='')
lines = stream.readlines(2)
stream.close()
except Exception as e:
print('An error occurred: ', e)
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
try:
stream = open('animals.txt')
for line in stream:
print(line, end='')
except Exception as e:
21 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
print('An error occurred: ', e)
Ex 5:
f=open("abc.txt","r")
print(f.read(3))
print(f.readline())
print(f.read(4))
print("Remaining data")
print(f.read())
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Binary File Basics
Binary files in Python store data in a format not meant to be read by humans.
These files can contain various types of data, such as images, audio, videos,
compressed archives, or any other form of data that is not in plain text.
Working with binary files in Python requires reading and writing data as raw
bytes.
22 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Ex:
# Open a file for writing in binary mode in the current directory
with open('TumBin.bin', 'wb') as binary_file:
# Define some data to write
data = bytes([0x48, 0x65, 0x6C, 0x6C, 0x6F]) # This represents the ASCII values
for 'Hello'
23 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
# Write the data to the file
binary_file.write(data)
print("Binary file has been created successfully in the current directory.")
Explanation:
=> with open('example.bin', 'wb') as binary_file:
=> This line opens a file named 'example.bin' in binary write mode ('wb').
The with statement is used here to ensure the file is correctly closed after
writing.
=> [0x48, 0x65, 0x6C, 0x6C, 0x6F]. These hexadecimal values represent the ASCII
character 'Hello'.
=> This line writes the binary data (the ASCII values for 'Hello') to the binary file
opened earlier.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Reading a binary file
In Python, when opening a binary file for reading, use the 'rb' mode, specifically
designed for binary data.
Ex:
# Opening a binary file for reading
with open('example.bin', 'rb') as file:
binary_data = file.read()
print(binary_data)
24 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
bytearray()
bytearray() method returns a bytearray object which is an array of the given
bytes.
It gives a mutable sequence of integers in the range 0 <= x < 256.
Syntax
bytearray(source, encoding, errors)
Parameters:
=> source[optional]: Initializes the array of bytes
=> encoding[optional]: Encoding of the string
=> errors[optional]: Takes action when encoding fails
Returns:
Returns an array of bytes of the given size.
source parameter can be used to initialize the array in few
different ways
bytearray() Function on String
In this example, we are taking a String and performing the bytearray() function on it.
The bytearray() encodes the string and converts it to byte array object in python using str.encode().
str = "CodeWithDDSingh"
# encoding the string with unicode 8 and 16
array1 = bytearray(str, 'utf-8')
array2 = bytearray(str, 'utf-16')
print(array1)
print(array2)
25 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
bytearray() Function on an Integer
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Reading binary files: read() vs readinto()
The read() method reads all the contents of the file into the memory. This method creates an object of a
special class called bytes
Ex
try:
bf = open('file.bin', 'rb')
newly_created = bf.read()
bf.close()
except Exception as e:
print('An error occured:', e)
The bytes class is very similar to bytearray. There is one difference: the bytes class is immutable (once
created, it can't be changed).
If, for some reason, you need a bytearray object rather than a bytes object, you can simply wrap
the bf.read() method call like this: bytearray(bf.read()). This will return a bytearray rather than
a bytes object.
26 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Another option to get a bytearray is to create it manually and then use
bf.readinto(bytearray) instead of bf.read()
Ex:
data = bytearray(10)
try:
bf = open('file.bin', 'rb')
bf.readinto(data)
bf.close()
except Exception as e:
print('An error occured:', e)
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Predefined Streams:
In Python, streams refer to objects that provide a way to read data from and write data to various
input/output channels, such as files, network connections, or in-memory buffers.
Streams abstract the details of reading and writing, providing a uniform interface for handling I/O
operations.
The most common types of streams are
=> File Streams: For reading from and writing to files.
=> Standard Input/Output Streams: For interacting with the console or terminal.
=> Network Streams: For communicating over network connections.
=> In-Memory Streams: For reading and writing to memory buffers.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
27 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Streams in Python are typically handled using the built-in open() function and the io module, which
provide various classes and methods for stream operations.
Using In-Memory Streams
Python also provides in-memory streams via the io module, which can be useful for manipulating string
data as if it were file data.
StringIO for In-Memory Text Stream:
from io import StringIO
# Create an in-memory text stream
text_stream = StringIO()
# Write to the in-memory stream
text_stream.write("This is a text stream example.\n")
text_stream.write("It behaves like a file object.\n")
# Move to the beginning of the stream
text_stream.seek(0)
# Read from the in-memory stream
content = text_stream.read()
print(content)
StringIO(): Creates an in-memory stream for text.
text_stream.write(): Writes to the in-memory stream.
text_stream.seek(0): Moves the cursor to the beginning of the stream for reading.
text_stream.read(): Reads the entire content of the in-memory stream.
28 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
BytesIO for In-Memory Binary Stream:
from io import BytesIO
# Create an in-memory binary stream
binary_stream = BytesIO()
# Write binary data to the in-memory stream
binary_stream.write(b'This is a binary stream example.\n')
binary_stream.write(b'It behaves like a file object.\n')
# Move to the beginning of the stream
binary_stream.seek(0)
# Read binary data from the in-memory stream
content = binary_stream.read()
print(content)
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
BytesIO(): Creates an in-memory stream for binary data.
binary_stream.write(): Writes binary data to the in-memory stream.
binary_stream.seek(0): Moves the cursor to the beginning of the stream for reading.
binary_stream.read(): Reads the entire content of the in-memory stream as bytes.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Predefined Streams
import sys
sys.stdout.write('hello')
sys.stdout.write(str(3))
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
29 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Ex:
import sys
for line in sys.stdin:
if line.rstrip() == 'q':
break
print(line)
print('You pressed q, so I want to quit now. Bye!')
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
try:
stream = open('nonexistent.txt')
stream.close()
except Exception as e:
print('An error occurred: ', e)
Ex:
try:
stream = open('nonexistent.txt')
stream.close()
except Exception as e:
print(e.errno)
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
30 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Ex:
from os import strerror
try:
stream = open('nonexistent.txt')
stream.close()
except Exception as e:
print(strerror(e.errno))
31 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)