[go: up one dir, main page]

0% found this document useful (0 votes)
69 views46 pages

Unit - 3 - III Cs - Python (1)

Uploaded by

jagethiramesh
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)
69 views46 pages

Unit - 3 - III Cs - Python (1)

Uploaded by

jagethiramesh
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/ 46

Sri Ganesh College of Arts & Science – Salem- 14.

Department of Computer Science & Applications


Study Material – (2023-24 Even Semester)

Sub: Programming in Python Paper Code: 21UCS10 Class: III B.Sc CS


Sub I/c: Date: HOD:

UNIT – III
Mapping type: Dictionaries – Mapping type operators – Mapping type Built-in and Factory Functions -
Mapping type built in methods – Conditionals and loops – if statement – else Statement – elif statement –
conditional expression while statement – for statement – break statement – continue statement – pass
statement – Iterators and the iter( ) function - Files and Input / Output – File objects – File built-in functions
– File built – in methods – File built-in attributes – Standard files – command line arguments.

MAPPING TYPES
 A mapping object maps values of one type (the key type) to arbitrary objects. Mappings are mutable
objects.
DICTIONARY
 There is currently only one standard mapping type, the dictionary.
 A dictionary’s keys are almost arbitrary values. The only types of values not acceptable as keys are
values containing lists or dictionaries or other mutable types that are compared by value rather than
by object identity.
 Numeric types used for keys obey the normal rules for numeric comparison: if two numbers
compare equal (e.g., 1 and 1.0) then they can be used interchangeably to index the same dictionary
entry.
MAPPING TYPES OPERATORS
 Objects are used to map hash table values to arbitrary objects.
 In python there is mapping type called dictionary.
 It is mutable.
 The keys of the dictionary are arbitrary. As the value, we can use different kind of elements like
lists, integers or any other mutable type objects.

1
 Some dictionary related methods and operations are – Dictionaries are created by placing a comma –
separated list of key: value pairs with in braces, for
example: {'jack': 4098, 'sjoerd': 4127} or {4098: 'jack', 4127: 'sjoerd'}.
 The operations in the following table are defined on mappings (where a is a mapping, k is a key
and x is an arbitrary object).

Operation Result Notes

len(a) The number of items in a

a[k] The item of a with key k 1

a[k] = x Set a[k] to x

del a[k] Remove a[k] from a (1)

a.clear() Remove all items from a

a.copy() A (shallow) copy of a

a.has_key(k) 1 if a has a key k, else 0

a.items() A copy of a’s list of (key, value) pairs 2

a.keys() A copy of a’s list of keys 2

a.update(b) For k, v in b.items(): a[k] = v 3

a.values() A copy of a’s list of values 2

a.get(k[, f]) The value of a with key k 4

Method len(d)
 The len() method returns the number of elements in the dictionary.
Operation d[k]
 It will return the item of d with the key ‘k’. It may raise KeyError if the key is not mapped.

2
Method iter(d)
 This method will return an iterator over the keys of dictionary. We can also perform this takes by
using iter(d.keys()).
Method get(key[, default])
 The get() method will return the value from the key. The second argument is optional. If the key is
not present, it will return the default value.
Method items()
 It will return the items using (key, value) pairs format.
Method keys()
 Return the list of different keys in the dictionary.
Method values()
 Return the list of different values from the dictionary.
Method update(elem)
 Modify the element elem in the dictionary.
Example Code
Live Demo
myDict = {'ten' : 10, 'twenty' : 20, 'thirty' : 30, 'forty' : 40}
print(myDict)
print(list(myDict.keys()))
print(list(myDict.values()))

#create items from the key-value pairs


print(list(myDict.items()))

myDict.update({'fifty' : 50})
print(myDict)
Output
{'ten': 10, 'twenty': 20, 'thirty': 30, 'forty': 40}
['ten', 'twenty', 'thirty', 'forty']
[10, 20, 30, 40]
[('ten', 10), ('twenty', 20), ('thirty', 30), ('forty', 40)]
{'ten': 10, 'twenty': 20, 'thirty': 30, 'forty': 40, 'fifty': 50}

3
 So finally, A dictionary maps keys to values. Keys need to be hash able objects, while values can be
of any arbitrary type. Dictionaries are mutable objects.

MAPPING TYPE BUILT IN AND FACTORY FUNCTIONS


 In Python, mapping types primarily refer to dictionaries (dict).
 Dictionaries are mutable, unordered collections of key-value pairs, and they allow you to map keys
to values.
 There are different ways to create dictionaries in Python, including using built-in methods and
factory functions. Here's an explanation of both:
Built-in Methods:
 Python provides built-in methods for creating and manipulating dictionaries. Some common built-in
methods include:
Literal Syntax:
 You can create a dictionary using literal syntax, where you define key-value pairs within curly
braces {}:
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
dict() Constructor:
 The dict() constructor can be used to create a dictionary. You can pass key-value pairs as arguments
or provide an iterable of key-value pairs:
my_dict = dict(key1='value1', key2='value2', key3='value3')
fromkeys() Method:
 The fromkeys() method creates a new dictionary with specified keys and a default value:
keys = ['key1', 'key2', 'key3']
default_value = 'default'
my_dict = dict.fromkeys(keys, default_value)
Factory Functions:
 In addition to built-in methods, there are factory functions provided by the collections module that
allow you to create specialized mapping types. One notable factory function is defaultdict.
defaultdict:
 defaultdict is a dictionary subclass that provides a default value for each new key. This can be useful
when you want to avoid key errors.
from collections import defaultdict
# Create a defaultdict with default value as int (default is 0)
4
my_default_dict = defaultdict(int)
my_default_dict['key1'] += 1
default dict is particularly handy when you are counting occurrences or initializing values in a dictionary.
These are some ways to create and work with mapping types in Python. Choose the method that best suits
your needs based on the specific requirements of your code.

MAPPING TYPE BUILT IN METHODS


 In Python, mapping types, specifically dictionaries (dict), come with a variety of built-in methods
that allow you to perform operations on them.
 Here's an overview of some common built-in methods for dictionaries:
1.clear():
Removes all items from the dictionary.
my_dict = {'key1': 'value1', 'key2': 'value2'}
my_dict.clear()

2.copy():
Returns a shallow copy of the dictionary.
original_dict = {'key1': 'value1', 'key2': 'value2'}
copy_dict = original_dict.copy()

3.get(key, default=None):
Returns the value for the specified key. If the key is not found, it returns the default value (default is
None if not specified).
my_dict = {'key1': 'value1', 'key2': 'value2'}
value = my_dict.get('key3', 'default_value')

4.items():
Returns a view of the dictionary's key-value pairs as tuples.
my_dict = {'key1': 'value1', 'key2': 'value2'}
items = my_dict.items()

5
5.keys():
Returns a view of the dictionary's keys.
my_dict = {'key1': 'value1', 'key2': 'value2'}
keys = my_dict.keys()

6.values():
Returns a view of the dictionary's values.
my_dict = {'key1': 'value1', 'key2': 'value2'}
values = my_dict.values()

7.pop(key, default):
Removes and returns the value for the specified key. If the key is not found, it returns the default
value (or raises a KeyError if default is not provided).
my_dict = {'key1': 'value1', 'key2': 'value2'}
value = my_dict.pop('key1', 'default_value')

8.popitem():
Removes and returns an arbitrary (key, value) pair as a tuple. Raises a KeyError if the dictionary is
empty.
my_dict = {'key1': 'value1', 'key2': 'value2'}
item = my_dict.popitem()

9.update(iterable):
Updates the dictionary with elements from another iterable (e.g., another dictionary or a sequence of
key-value pairs).
my_dict = {'key1': 'value1', 'key2': 'value2'}
my_dict.update({'key3': 'value3', 'key4': 'value4'})

10.setdefault(key, default):
Returns the value for the specified key. If the key is not found, inserts the key with the specified
default value.
my_dict = {'key1': 'value1', 'key2': 'value2'}
value = my_dict.setdefault('key3', 'default_value')

6
11.del statement:
Deletes the key-value pair with the specified key.
my_dict = {'key1': 'value1', 'key2': 'value2'}
del my_dict['key1']
These are just a few examples of the built-in methods for dictionaries in Python.

CONDITIONALS AND LOOPS


 In Python, conditional loops are created using if, elif (else if), and else statements to control the flow
of the program based on certain conditions. Additionally, loops like while or for can be used in
conjunction with conditional statements to create more complex control structures.
 Python supports the usual logical conditions from mathematics:
o Equals: a == b
o Not Equals: a != b
o Less than: a < b
o Less than or equal to: a <= b
o Greater than: a > b
o Greater than or equal to: a >= b
o these conditions can be used in several ways, most commonly in "if statements" and loops.
o An "if statement" is written by using the if keyword.
Examples:
a = 33
b = 200
if b > a:
print("b is greater than a") o/p: b is greater than a
Else
 The else keyword catches anything which isn't caught by the preceding conditions.
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
7
else:
print("a is greater than b")
 In this example a is greater than b, so the first condition is not true, also the elif condition is not true,
so we go to the else condition and print to screen that "a is greater than b".
 we can also have an else without the elif:
Example
a = 200
b = 33
if b > 2a:
print("b is greater than a")
else:
print("b is not greater than a")
Elif
 The elif keyword is Python's way of saying "if the previous conditions were not true, then try this
condition".
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
 In this example a is equal to b, so the first condition is not true, but the elif condition is true, so we
print to screen that "a and b are equal".
 If you have only one statement to execute, one for if, and one for else, you can put it all on the same
line:
Example
One line if else statement:
a=2
b = 330
print("A") if a > b else print("B")
Here's an example of a simple conditional loop using if, elif, and else statements:

8
Example 1: Simple conditional loop
x = 10
if x > 0:
print("x is positive")
elif x == 0:
print("x is zero")
else:
print("x is negative")
In this example, the program checks the value of the variable x and prints a message based on the
condition.

 He for loop in Python has the ability to iterate over the items of any sequence, such as a list, tuple or
a string.
Syntax
for iterating_var in sequence:
statements(s)
 If a sequence contains an expression list, it is evaluated first. Then, the first item (at 0th index) in the
sequence is assigned to the iterating variable iterating_var.
 Next, the statements block is executed. Each item in the list is assigned to iterating_var, and the
statement(s) block is executed until the entire sequence is exhausted.
The following flow diagram illustrates the working of for loop –

 Since the loop is executed for each member element in a sequence, there is no need for explicit
verification of Boolean expression controlling the loop (as in while loop).

9
 The sequence objects such as list, tuple or string are called iterables, as the for loop iterates through
the collection. Any iterator object can be iterated by the for loop.
 The view objects returned by items(), keys() and values() methods of dictionary are also iterables,
hence we can run a for loop with these methods.
 Python's built-in range() function returns an iterator object that streams a sequence of numbers. We
can run a for loop with range as well.
Using "for" with a String
 A string is a sequence of Unicode letters, each having a positional index. The following example
compares each character and displays if it is not a vowel ('a', 'e', 'I', 'o' or 'u')
Example
zen = '''
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
'''
for char in zen:
if char not in 'aeiou':
print (char, end='')
Output
On executing, this code will produce the following output −
Using "for" with a Tuple
 Python's tuple object is also an indexed sequence, and hence we can traverse its items with
a for loop.
Example
In the following example, the for loop traverses a tuple containing integers and returns the total
of all numbers.
numbers = (34,54,67,21,78,97,45,44,80,19)
total = 0
for num in numbers:
total+=num
print ("Total =", total) Output
On executing, this code will produce the following output - Total = 539

10
Using "for" with a List
 Python's list object is also an indexed sequence, and hence we can traverse its items with a for loop.
Example
In the following example, the for loop traverses a list containing integers and prints only those which
are divisible by 2.
numbers = [34,54,67,21,78,97,45,44,80,19]
total = 0
for num in numbers:
if num%2 == 0:
print (num)
Output
On executing, this code will produce the following output −
34
54
78
44
80
Using "for" with a Range Object
 Python's buil-in range() function returns a range object.
 Python's range object is an iterator which generates an integer with each iteration.
 The object contains integrrs from start to stop, separated by step parameter.
Syntax
The range() function has the following syntax − range(start, stop, step)
Parameters
Start − Starting value of the range. Optional. Default is 0
Stop − The range goes upto stop-1
Step − Integers in the range increment by the step value. Option, default is 1.
Return Value
The range() function returns a range object. It can be parsed to a list sequence.
Example
numbers = range(5)
''
start is 0 by default,

11
step is 1 by default,
range generated from 0 to 4
'''
print (list(numbers))
# step is 1 by default, range generated from 10 to 19
numbers = range(10,20)
print (list(numbers))
# range generated from 1 to 10 increment by step of 2
numbers = range(1, 10, 2)
print (list(numbers))
Output
On executing, this code will produce the following output −
[0, 1, 2, 3, 4]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[1, 3, 5, 7, 9].
Using "for" Loop with Sequence Index
 To iterate over a sequence, we can obtain the list of indices using the range() function
Indices = range(len(sequence))
We can then form a for loop as follows:
numbers = [34,54,67,21,78]
indices = range(len(numbers))
for index in indices:
print ("index:",index, "number:",numbers[index])
On executing, this code will produce the following output −
index: 0 number: 34
index: 1 number: 54
index: 2 number: 67
index: 3 number: 21
index: 4 number: 78
Using "for" with Dictionaries
Unlike a list, tuple or a string, dictionary data type in Python is not a sequence, as the items do not have
a positional index. However, traversing a dictionary is still possible with different techniques.
Running a simple for loop over the dictionary object traverses the keys used in it.

12
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
for x in numbers:
print (x)
On executing, this code will produce the following output −
10
20
30
40
WHILE LOOPS
 Normally, flow of execution of steps in a computer program goe from start to end. However, instead
of the next step, if the flow is redirected towards any earlier step, it constitutes a loop.
 A while loop statement in Python programming language repeatedly executes a target statement as
long as a given boolean expression is true.
Syntax
 The syntax of a while loop in Python programming language is −
while expression:
statement(s)
 The while keyword is followed by a boolean expression, and then by colon symbol, to start an
indented block of statements.
 Here, statement(s) may be a single statement or a block of statements with uniform indent. The
condition may be any expression, and true is any non-zero value. The loop iterates while the boolean
expression is true.
 As soon as the expression becomes false, the program control passes to the line immediately
following the loop.
 If it fails to turn false, the loop continues to run, and doesn't stop unless forcefully stopped. Such a
loop is called infinite loop, which is undesired in a computer program
Example
 In Python, all the statements indented by the same number of character spaces after a programming
construct are considered to be part of a single block of code.
 Python uses indentation as its method of grouping statements.
count=0
while count<5:
count+=1

13
print ("Iteration no. {}".format(count))
print ("End of while loop")
 We initialize count variable to 0, and the loop runs till "count<5".
 In each iteration, count is incremented and checked. If it's not 5 next repetion takes place. Inside the
looping block, instantenous value of count is printed. When the while condition becomes false, the
loop terminates, and next statement is executed, here it is End of while loop message.
Output
On executing, this code will produce the following output −
Iteration no. 1
Iteration no. 2
Iteration no. 3
Iteration no. 4
Iteration no. 5
End of while loop
The following flow diagram illustrates the while loop −

The Infinite Loop


 A loop becomes infinite loop if a condition never becomes FALSE.
 we must be cautious when using while loops because of the possibility that this condition never
resolves to a FALSE value.
 This results in a loop that never ends. Such a loop is called an infinite loop.
 An infinite loop might be useful in client/server programming where the server needs to run
continuously so that client programs can communicate with it as and when required.
The while-else Loop
 Python supports having an else statement associated with a while loop statement.

14
 If the else statement is used with a while loop, the else statement is executed when the condition
becomes false before the control shifts to the main line of execution.
 The following flow diagram shows how to use else with while statement −

Example
 The following example illustrates the combination of an else statement with a while statement. Till
the count is less than 5, the iteration count is printed.
 As it becomes 5, the print statement in else block is executed, before the control is passed to the next
statement in the main program.
count=0
while count<5:
count+=1
print ("Iteration no. {}".format(count))
else:
print ("While loop over. Now in else block")
print ("End of while loop")

BREAK STATEMENT
 It terminates the current loop and resumes execution at the next statement, just like the traditional
break statement in C.
 The most common use for break is when some external condition is triggered requiring a hasty exit
from a loop. The break statement can be used in both while and for loops.
 If you are using nested loops, the break statement stops the execution of the innermost loop and start
executing the next line of code after the block.
Syntax
 The syntax for a break statement in Python is as follows −
break

15
Example
for letter in 'Python': # First Example
if letter == 'h':
break
print ('Current Letter :', letter)

var = 10 # Second Example


while var > 0:
print ('Current variable value :', var)
var = var -1
if var == 5:
break
print ("Good bye!")
When the above code is executed, it produces the following result −
Current Letter : P
Current Letter : y
Current Letter : t
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Good bye!
CONTINUE STATEMENT
 The continue statement in Python returns the control to the beginning of the current loop. When
encountered, the loop starts next iteration without executing the remaining statements in the current
iteration.
 The continue statement can be used in both while and for loops.
Syntax
continue

16
Flow Diagram
 The flow diagram of the continue statement looks like this −

 The continue statement is just the opposite to that of break. It skips the remaining statements in the
current loop and starts the next iteration.
Example
for letter in 'Python': # First Example
if letter == 'h':
continue
print ('Current Letter :', letter)
var = 10 # Second Example
while var > 0:
var = var -1
if var == 5:
continue
print ('Current variable value :', var)
print ("Good bye!")
When the above code is executed, it produces the following output −
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Current variable value : 9
Current variable value : 8
Current variable value : 7

17
Current variable value : 6
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Current variable value : 0
Good bye!
PASS STATEMENT
 The Python pass statement is used when a statement is required syntactically but you do not want
any command or code to execute.
 The Python pass statement is a null operation; nothing happens when it executes.
 The pass statement is also useful in places where your code will eventually go, but has not been
written yet, i.e., in stubs).
Syntax
pass

Example
The following code shows how you can use the pass statement in Python –
for letter in 'Python':
if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)
print ("Good bye!")
When the above code is executed, it produces the following output −
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!

18
Dummpy Infinite Loop with Pass
 This is simple enough to create an infinite loop using pass statement. For instance, if you want to
code an infinite loop that does nothing each time through, do it with a pass:
while True: pass # Type Ctrl-C to stop
 Because the body of the loop is just an empty statement, Python gets stuck in this loop. As explained
earlier pass is roughly to statements as None is to objects — an explicit nothing.
Using Ellipses ... as pass Alternative
 Python 3.X allows ellipses coded as three consecutive dots ...to be used in place of pass statement.
This ... can serve as an alternative to the pass statement.
 For example if we create a function which does not do anything especially for code to be filled in
later, then we can make use of ...
def func1():
... # Alternative to pass
def func2(): ... # Works on same line too
func1() # Does nothing if called
func2() # Does nothing if called

ITERATOR AND THE ITER()FUNCTIONS


 In Python, an iterator is an object that implements the iterator protocol, which consists of the
__iter__() and __next__() methods.
 An iterator is used to represent a stream of data and allows you to traverse the elements of a
sequence, such as a list or a tuple, one at a time.
 Here's a brief explanation of the iterator protocol and the iter() function:
Iterator Protocol:
1.iter__() Method:
 This method returns the iterator object itself. It is called when an iterator is created for an object.
2.next__() Method:
 This method returns the next value from the iterator. If there are no more items to return, it should
raise the StopIteration exception.
 Here's a simple example of an iterable and an iterator:
class MyIterator:
def __iter__(self):
self.current = 1

19
return self
def __next__(self):
if self.current <= 5:
result = self.current
self.current += 1
return result
else:
raise StopIteration
my_iterator = MyIterator()
for num in my_iterator:
print(num)
iter() Function:
 The iter() function is a built-in function in Python that takes an iterable object and returns an iterator.
 If the object passed to iter() has an __iter__() method, it returns the result of that method. If the
object has a __getitem__() method, iter() creates an iterator that indexes from 0 up to len(object) - 1.
Example using iter():
my_list = [1, 2, 3, 4, 5]
my_iterator = iter(my_list)
print(next(my_iterator)) # prints 1
print(next(my_iterator)) # prints 2
In many cases, the for loop implicitly uses the iter() function to create an iterator and the __next__()
method to retrieve the next element until a StopIteration exception is raised.
Understanding iterators and the iterator protocol is crucial for working with Python's for loop and
comprehending how looping constructs operate in the language.

FILES AND INPUT OUTPUT OBJECTS


 In Python, input and output operations are commonly performed using files.
 The built-in open() function is used to open a file and create a file object, which is then used for
reading or writing data. Here's an overview of file handling in Python:
Opening a File:
 To open a file, you use the open() function. It takes two arguments: the filename and the mode (read,
write, append, etc.).

20
# Opening a file for reading
file_path = "example.txt"
with open(file_path, "r") as file:
# Perform operations on the file
content = file.read()
print(content)
# File is automatically closed when exiting the 'with' block
Reading from a File:
 After opening a file for reading, you can use various methods like read(), readline(), or readlines() to
read its content.
with open("example.txt", "r") as file:
content = file.read() # Reads the entire file
print(content)
Writing to a File:
 To write to a file, you open it in write mode ("w"). Be cautious, as this will overwrite the existing
content of the file.
with open("example.txt", "w") as file:
file.write("Hello, World!\n")
file.write("This is a new line.")
Appending to a File:
 To append to a file, open it in append mode ("a"). This will add new content at the end of the file.
with open("example.txt", "a") as file:
file.write("\nAppending a new line.")
Reading and Writing in Binary Mode:
 You can also work with files in binary mode by specifying "rb" (read binary) or "wb" (write binary).
with open("binary_file.bin", "wb") as binary_file:
binary_file.write(b'\x48\x65\x6c\x6c\x6f') # Writing binary data
with open("binary_file.bin", "rb") as binary_file:
content = binary_file.read() # Reading binary data
print(content)

21
Using input() for User Input:
 The input() function is used to take user input from the console.
user_input = input("Enter something: ")
print("You entered:", user_input)
 These are basic examples of file handling and user input/output in Python. They cover common
scenarios, but file handling can become more complex depending on your specific requirements,
such as working with different file formats or handling exceptions during file operations.

FILE BUILT IN FUNCTIONS IN PYTHON


 In Python, there are several built-in functions and methods associated with file handling.
 These functions allow you to perform various operations on files, such as opening, reading, writing,
and closing. Here are some commonly used file-related functions in Python:
open() Function:
Opens a file and returns a file object.
file = open("example.txt", "r")
read(size) Method:
Reads and returns the specified number of bytes from the file. If no size is specified, it reads the
entire file.
content = file.read(10) # Reads the first 10 characters
readline() Method:
Reads and returns the next line from the file.
line = file.readline()
readlines() Method:
Reads all the lines from the file and returns them as a list of strings.
lines = file.readlines()
write(string) Method:
Writes the specified string to the file.
file.write("Hello, World!")
writelines(lines) Method:
Writes a list of lines to the file.
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
file.writelines(lines)

22
close() Method:
Closes the file. It's important to close the file when you're done with it to free up system resources.
file.close()
flush() Method:
Flushes the internal buffer, ensuring that all data is written to the file.
file.flush()
seek(offset, whence) Method:
Moves the file cursor to the specified position. The whence parameter determines the reference point
for the offset (0 for the beginning, 1 for the current position, 2 for the end).
file.seek(0, 0) # Move to the beginning of the file
tell() Method:
Returns the current position of the file cursor.
position = file.tell()
with Statement:
 A context manager that simplifies the process of opening and closing files by automatically closing
the file when exiting the block.
with open("example.txt", "r") as file:
content = file.read()
 These are some of the basic file-related functions and methods in Python. File handling in Python is
versatile, and depending on your requirements, you may need to explore additional functionalities
and consider error handling, especially when dealing with file operations.

FILE BUILT IN ATTRIBUTES IN PYTHON


 In Python, file objects have several built-in attributes that provide information about the file.
 These attributes can be accessed after opening a file using the open() function. Here are some
commonly used file-related attributes:
Name Attribute:Returns the name of the file.
file = open("example.txt", "r")
print(file.name)
mode Attribute:
 Returns the access mode with which the file was opened (e.g., "r" for read, "w" for write, "a" for
append).
file = open("example.txt", "r")

23
print(file.mode)
closed Attribute:
 Returns True if the file is closed, and False otherwise.
file = open("example.txt", "r")
print(file.closed) # False
file.close()
print(file.closed) # True
encoding Attribute:
 Returns the encoding used for the file. This attribute is available only if the file was opened with an
encoding parameter.
file = open("example.txt", "r", encoding="utf-8")
print(file.encoding)
buffer Attribute:
 Returns the underlying buffer object if the file uses binary mode.
file = open("binary_file.bin", "rb")
print(file.buffer)
errors Attribute:
 Returns the Unicode error handling scheme used for decoding and encoding file data. This attribute
is available only if the file was opened with an encoding parameter.
file = open("example.txt", "r", encoding="utf-8", errors="ignore")
print(file.errors)
 These attributes provide information about the file object and its properties.
 Keep in mind that some attributes, such as encoding and errors, are specific to text mode files.
 When working with binary mode files, these attributes may not be present.
 It's important to note that file attributes are read-only and cannot be modified directly.
 They provide information about the state and properties of the file object.

FILES INPUT / OUTPUT


 This concept covers all the basic I/O functions available in Python.
Printing to the Screen
 The simplest way to produce output is using the print statement where you can pass zero or more
expressions separated by commas.

24
 This function converts the expressions you pass into a string and writes the result to standard output
as follows −
Live Demo
#!/usr/bin/python
print"Python is really a great language,","isn't it?"
This produces the following result on your standard screen −
Python is really a great language, isn't it?
Reading Keyboard Input
 Python provides two built-in functions to read a line of text from standard input, which by default
comes from the keyboard.
 These functions are −
o raw_input
o input
The raw_input Function
 The raw_input([prompt]) function reads one line from standard input and returns it as a string
(removing the trailing newline).
#!/usr/bin/python

str = raw_input("Enter your input: ")


print"Received input is : ", str
 This prompts you to enter any string and it would display same string on the screen. When I typed
"Hello Python!", its output is like this −
Enter your input: Hello Python
Received input is : Hello Python
The input Function
 The input([prompt]) function is equivalent to raw_input, except that it assumes the input is a valid
Python expression and returns the evaluated result to you.
#!/usr/bin/python
str = input("Enter your input: ")
print"Received input is : ", str
This would produce the following result against the entered input −
Enter your input: [x*5 for x in range(2,10,2)]
Recieved input is : [10, 20, 30, 40]

25
Opening and Closing Files
 Until now, you have been reading and writing to the standard input and output. Now, we will see
how to use actual data files.
 Python provides basic functions and methods necessary to manipulate files by default. You can do
most of the file manipulation using a file object.
The open Function
 Before you can read or write a file, you have to open it using Python's built-in open() function. This
function creates a file object, which would be utilized to call other support methods associated with
it.
Syntax
file object = open(file_name [, access_mode][, buffering])
Here are parameter details −
 file_name − The file_name argument is a string value that contains the name of the file that you
want to access.
 access_mode − The access_mode determines the mode in which the file has to be opened, i.e., read,
write, append, etc. A complete list of possible values is given below in the table. This is optional
parameter and the default file access mode is read (r).
 buffering − If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line
buffering is performed while accessing a file.
 If you specify the buffering value as an integer greater than 1, then buffering action is performed
with the indicated buffer size. If negative, the buffer size is the system default(default behavior).
 Here is a list of the different modes of opening a file −

Modes & Description


Sr.No.

r
1 Opens a file for reading only. The file pointer is placed at the beginning of the
file. This is the default mode.

rb
2 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.

26
r+
3 Opens a file for both reading and writing. The file pointer placed at the beginning
of the file.

rb+
4 Opens a file for both reading and writing in binary format. The file pointer placed
at the beginning of the file.

w
5 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.

wb
6 Opens a file for writing only in binary format. Overwrites the file if the file
exists. If the file does not exist, creates a new file for writing.

w+
7 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.

wb+
Opens a file for both writing and reading in binary format. Overwrites the
8
existing file if the file exists. If the file does not exist, creates a new file for
reading and writing.

a
Opens a file for appending. The file pointer is at the end of the file if the file
9
exists. That is, the file is in the append mode. If the file does not exist, it creates a
new file for writing.

ab
Opens a file for appending in binary format. The file pointer is at the end of the
10
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.

27
a+
Opens a file for both appending and reading. The file pointer is at the end of the
11
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.

ab+
Opens a file for both appending and reading in binary format. The file pointer is
12
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.
 Here is a list of all attributes related to file object −

Sr.No. Attribute & Description

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

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

file.name
3
Returns name of the file.

file.softspace
4
Returns false if space explicitly required with print, true otherwise.

Example
Live Demo
#!/usr/bin/python
# Open a file
fo = open("foo.txt","wb")
print"Name of the file: ", fo.name
print"Closed or not : ", fo.closed
28
print"Opening mode : ", fo.mode
print"Softspace flag : ", fo.softspace
This produces the following result −
Name of the file: foo.txt
Closed or not : False
Opening mode : wb
Softspace flag : 0

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()
Example
Live Demo
#!/usr/bin/python
# Open a file
fo = open("foo.txt","wb")
print"Name of the file: ", fo.name
# Close opend file
fo.close()
This produces the following result −
Name of the file: foo.txt
Reading and Writing Files
 The file object provides a set of access methods to make our lives easier. We would see how to

use read() and write() methods to read and write files.


The write() Method
 The write() method writes any string to an open file. It is important to note that Python strings can
have binary data and not just text.
 The write() method does not add a newline character ('\n') to the end of the string −

29
Syntax
fileObject.write(string)
Here, passed parameter is the content to be written into the opened file.
Example
#!/usr/bin/python
# Open a file
fo = open("foo.txt","wb")
fo.write("Python is a great language.\nYeah its great!!\n")
# Close opend file
fo.close()
 The above method would create foo.txt file and would write given content in that file

 and finally it would close that file. If you would open this file, it would have following content.

Python is a great language.


Yeah its great!!
The read() Method
 The read() method reads a string from an open file. It is important to note that Python strings can

have binary data. apart from text data.


Syntax
 fileObject.read([count])

 Here, passed parameter is the number of bytes to be read from the opened file. This

 method starts reading from the beginning of the file and if count is missing, then it

 tries to read as much as possible, maybe until the end of file.

Example
 Let's take a file foo.txt, which we created above.

#!/usr/bin/python
# Open a file
fo = open("foo.txt","r+")
str = fo.read(10);
print"Read String is : ", str
# Close opend file
fo.close()
This produces the following result −
Read String is : Python is

30
File Positions
 The tell() method tells you the current position within the file; in other words, the next read or write
will occur at that many bytes from the beginning of the file.
 The seek(offset[, from]) method changes the current file position. The offset argument indicates the
number of bytes to be moved.
 The from argument specifies the reference position from where the bytes are to be moved.
Renaming and Deleting Files
 Python os module provides methods that help you perform file-processing operations, such as
renaming and deleting files.
 To use this module you need to import it first and then you can call any related functions.
The rename() Method
The rename() method takes two arguments, the current filename and the new filename.
Syntax
os.rename(current_file_name, new_file_name)
Example
Following is the example to rename an existing file test1.txt −
#!/usr/bin/python
import os
# Rename a file from test1.txt to test2.txt
os.rename("test1.txt","test2.txt")
The remove() Method
 You can use the remove() method to delete files by supplying the name of the file to be deleted as

the argument.
Syntax
os.remove(file_name)
Example
Following is the example to delete an existing file test2.txt −
#!/usr/bin/python
import os
# Delete file test2.txt
os.remove("text2.txt")

31
Directories in Python
 All files are contained within various directories, and Python has no problem handling these too.
 The os module has several methods that help you create, remove, and change directories.
The mkdir() Method
 we can use the mkdir() method of the os module to create directories in the current directory.
 we need to supply an argument to this method which contains the name of the directory to be
created.
Syntax
os.mkdir("newdir")
Example
Following is the example to create a directory test in the current directory −
#!/usr/bin/python
import os

# Create a directory "test"


os.mkdir("test")
The chdir() Method
 We can use the chdir() method to change the current directory.

 The chdir() method takes an argument, which is the name of the directory that you want to make the

current directory.
Syntax
os.chdir("newdir")
Following is the example to go into "/home/newdir" directory −
#!/usr/bin/python
import os

# Changing a directory to "/home/newdir"


os.chdir("/home/newdir")
The getcwd() Method
 The getcwd() method displays the current working directory.

Syntax
os.getcwd()
 Following is the example to give current directory −

32
#!/usr/bin/python
import os
# This would give location of the current directory
os.getcwd()
The rmdir() Method
 The rmdir() method deletes the directory, which is passed as an argument in the method.
 Before removing a directory, all the contents in it should be removed.
Syntax
os.rmdir('dirname')
 Following is the example to remove "/tmp/test" directory. It is required to give fully qualified name

of the directory, otherwise it would search for that directory in the current directory.
#!/usr/bin/python
import os
# This would remove "/tmp/test" directory.
os.rmdir("/tmp/test")
File & Directory Related Methods
 There are three important sources, which provide a wide range of utility methods to handle and

manipulate files & directories on Windows and Unix operating systems. They are as follows −
 File Object Methods: The file object provides functions to manipulate files.

 OS Object Methods: This provides methods to process files as well as directories.

File Handling in Python


 Apart from the most commonly used file handling functions:
 open()
 read()
 write()
 close()
 readline()
 write()
 writelines()
 tell()
 seek()
There are a lot more functions that are used for file handling in Python. Here is a list of some commonly
used file-handling functions in Python.

33
Function Description

open() Used to open a file.

readable() Used to check whether the file can be read or not.

readline() Used to read a single line from the file.

readlines() Used to read all the content in the form of lines.

read() Used to read whole content at a time.

writable() Used to check whether the file is writable or not.

write() Used to write a string to the file.

writelines() Used to write multiple strings at a time.

close() Used to close the file from the program.

 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.
o Open a file
o Read or write (perform operation)
o Close the file

FILE BUILT-IN FUNCTION [OPEN ()]


 Python has a built-in function open() to open a file.
 Which accepts two arguments, file name and access mode in which the file is accessed.
 The function returns a file object which can be used to perform various operations like reading, writing,
etc.
 Syntax:

 Fileobject = open (file-name, access-mode)

 file-name: It specifies the name of the file to be opened.


 access-mode: There are following access modes for opening a file
o close()

34
 The close() method used to close the currently opened file, after which no more writing or Reading 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()

readline()
 Python facilitates us to read the file line by line by using a function readline().
 The readline() method reads the lines of the file from the beginning, i.e., if we use the readline() method
two times, then we can get the first two lines of the file.
Syntax:

Fileobject.readline()

 function open() to open a file.


 method read() to read a file.

write()
 The write () method is used to write the content into file.
 To write some text to a file, we need to open the file using the open method with one of the following
access modes.
 It will overwrite the file if any file exists. The file pointer point at the beginning of the file in this mode.
Syntax:

Fileobject.write(content)

writelines()
The writelines () method is used to write multiple lines of content into file. To write some lines to a file
Syntax:

Fileobject.writelines(list)

list − This is the Sequence of the strings.


File Positions
Methods that set or modify the current position within the file

35
tell()
The tell() method returns the current file position in a file stream. You can change the current file position
with the seek() method.
Syntax:

Fileobject.tell()

seek()
The seek() method sets and returns the current file position in a file stream.
Syntax:

Fileobject.seek(offset)

FILE METHODS
 A file object is created using open() function.
 The file class defines the following methods with which different file IO operations can be done.
 The methods can be used with any file like object such as byte stream or network stream.

Sr.No. Methods & Description

file.close()
1
Close the file. A closed file cannot be read or written any more.

file.flush()
2 Flush the internal buffer, like stdio's fflush. This may be a no-op on some file-
like objects.

file_fileno()
3 Returns the integer file descriptor that is used by the underlying implementation
to request I/O operations from the operating system.

file.isatty()
4
Returns True if the file is connected to a tty(-like) device, else False.

next(file)
5
Returns the next line from the file each time it is being called.

36
file.read([size])
6 Reads at most size bytes from the file (less if the read hits EOF before obtaining
size bytes).

file.readline([size])
7 Reads one entire line from the file. A trailing newline character is kept in the
string.

file.readlines([sizehint])
Reads until EOF using readline() and return a list containing the lines. If the
8 optional sizehint argument is present, instead of reading up to EOF, whole lines
totalling approximately sizehint bytes (possibly after rounding up to an internal
buffer size) are read.

file.seek(offset[, whence])
9
Sets the file's current position

file.tell()
10
Returns the file's current position

file.truncate([size])
11 Truncates the file's size. If the optional size argument is present, the file is
truncated to (at most) that size.

file.write(str)
12
Writes a string to the file. There is no return value.

file.writelines(sequence)
13 Writes a sequence of strings to the file. The sequence can be any iterable object
producing strings, typically a list of strings.

Let us go through the above methods briefly.


Python - OS File/Directory Methods
The os module provides a big range of useful methods to manipulate files.
Most of the useful methods are listed here −

37
Sr.No. Methods with Description

1 os.close(fd)
Close file descriptor fd.

2 os.closerange(fd_low, fd_high)
Close all file descriptors from fd_low (inclusive) to fd_high (exclusive), ignoring
errors.
3 os.dup(fd)
Return a duplicate of file descriptor fd.
4 os.fdatasync(fd)
Force write of file with filedescriptor fd to disk.
5 os.fdopen(fd[, mode[, bufsize]])
Return an open file object connected to the file descriptor fd.
6 os.fsync(fd)
Force write of file with filedescriptor fd to disk.
7 os.ftruncate(fd, length)
Truncate the file corresponding to file descriptor fd, so that it is at most length bytes
in size.
8 os.lseek(fd, pos, how)
Set the current position of file descriptor fd to position pos, modified by how.
9 os.open(file, flags[, mode])
Open the file file and set various flags according to flags and possibly its mode
according to mode.
10 os.read(fd, n)
Read at most n bytes from file descriptor fd. Return a string containing the bytes
read. If the end of the file referred to by fd has been reached, an empty string is
returned.
11 os.tmpfile()
Return a new file object opened in update mode (w+b).
12 os.write(fd, str)
Write the string str to file descriptor fd. Return the number of bytes actually written.

38
FILE BUILT-IN ATTRIBUTES
Python Supports following built-in attributes, those are
 file.name - returns the name of the file which is already opened.
 file.mode - returns the access mode of opened file.
 file.closed - returns true, if the file closed, otherwise false.
 Examples:

f = open ("myfile.txt", "r")


print(f.name)
print(f.mode)
print(f.closed)
f.close()
print(f.closed)
output:
myfile.txt
r
False
True

Python program to print number of lines, words and characters in given file.

function open() to open a file.


method read() to read a file.
Python is the modern day language.
Python supports Files
python supports Strings

 In Python, file attributes provide information about a file, such as its size, creation time,
modification time, etc.
 The built-in os module and os.path module (deprecated in Python 3.10 and later) are commonly used
for working with file attributes.
 Here are some common file attributes and how you can retrieve them using Python:
File Path:
import os

39
file_path = 'example.txt'
print("File Path:", os.path.abspath(file_path))
File Size:
import os
file_path = 'example.txt'
size_in_bytes = os.path.getsize(file_path)
print("File Size (in bytes):", size_in_bytes)
File Creation Time:
import os
import datetime
file_path = 'example.txt'
creation_time = os.path.getctime(file_path)
creation_time_formatted = datetime.datetime.fromtimestamp(creation_time).strftime('%Y-%m-%d
%H:%M:%S')
print("File Creation Time:", creation_time_formatted)
File Modification Time:
import os
import datetime
file_path = 'example.txt'
modification_time = os.path.getmtime(file_path)
modification_time_formatted = datetime.datetime.fromtimestamp(modification_time).strftime('%Y-%m-%d
%H:%M:%S')
print("File Modification Time:", modification_time_formatted)
Is a Directory:
import os
file_path = 'example_directory'
is_directory = os.path.isdir(file_path)
print("Is a Directory:", is_directory)
Is a File:
import os
file_path = 'example.txt'
is_file = os.path.isfile(file_path)
print("Is a File:", is_file)

40
Python standard I/O
 There are three basic I/O connections: standard input, standard output and standard error. Standard
input is the data that goes to the program.
 The standard input comes from a keyboard. Standard output is where we print our data with the print
keyword.
 Unless redirected, it is the terminal console. The standard error is a stream where programs write
their error messages. It is usually the text terminal.
The standard input and output in Python are objects located in the sys module.

Object Description

sys.stdin standard input

sys.stdout standard output

sys.stderr standard error

Conforming to the UNIX philosophy, the standard I/O streams are file objects.
Python standard input
Standard input is the data that goes to the program.
read_name.py
#!/usr/bin/env python

# read_name.py

import sys

print('Enter your name: ', end='')

name = ''

sys.stdout.flush()

while True:

c = sys.stdin.read(1)
41
if c == '\n':
break

name = name + c

print('Your name is:', name)


The read method reads one character from the standard input. In our example we get a prompt saying
"Enter your name". We enter our name and press Enter. The Enter key generates the new
line character: \n.
$ ./read_name.py
Enter your name: Peter
Your name is: Peter
For getting input we can use higher level functions: input and raw_input .
The input function prints a prompt if it is given and reads the input.
input_example.py
#!/usr/bin/env python

# input_example.py

data = input('Enter value: ')

print('You have entered:', data)


$ ./input_example.py
Enter value: Hello there
You have entered: Hello there
Python standard output
The standard output is where we print our data.
std_output.py
#!/usr/bin/env python

# std_output.py

42
import sys

sys.stdout.write('Honore de Balzac, Father Goriot\n')


sys.stdout.write('Honore de Balzac, Lost Illusions\n')
In the example, we write some text to the standard output. This is in our case the terminal console. We use
the write method.
$ ./stdout.py
Honore de Balzac, Father Goriot
Honore de Balzac, Lost Illusions
The print function puts some text into the sys.stdout by default.
print_fun.py

#!/usr/bin/env python

# print_fun.py

print('Honore de Balzac')
print('The Splendors and Miseries of Courtesans', 'Gobseck', 'Father Goriot', sep=":")

vals = [1, 2, 3, 4, 5]

for e in vals:
print(e, end=' ')

print()
In this example, we use the sep and end parameters. The sep separates the printed objects and
the end defines what is printed at the end

COMMAND LINE ARGUMENTS


 Python Command Line Arguments provides a convenient way to accept some information at the
command line while running the program.
 The arguments that are given after the name of the Python script are known as Command Line
Arguments and they are used to pass some information to the program. For example
43
 $ python script.py arg1 arg2 arg3
 Here Python script name is script.py and rest of the three arguments - arg1 arg2 arg3 are command
line arguments for the program. There are following three Python modules which are helpful in
parsing and managing the command line arguments:
o sys module
o getopt module
o argparse module
1.sys module - System-specific parameters
 The Python sys module provides access to any command-line arguments via the sys.argv. This
serves two purposes −
sys.argv is the list of command-line arguments.
len(sys.argv) is the number of command-line arguments.
Here sys.argv[0] is the program ie. script name.
Example
 Consider the following script test.py −
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
 Now run above script as below. All the programs in this tutorial need to be run from the command
line, so we are unable to provide online compile & run option for these programs. Kindly try to run
these programs at your computer.
$ python test.py arg1 arg2 arg3
This produce following result −
Number of arguments: 4 arguments.
Argument List: ['test.py', 'arg1', 'arg2', 'arg3']
 As mentioned above, first argument is always script name and it is also being counted in number of
arguments.
Parsing Command-Line Arguments
 Python provided a getopt module that helps you parse command-line options and arguments. This
module provides two functions and an exception to enable command line argument parsing.
 getopt.getopt method
 This method parses command line options and parameter list. Following is simple syntax for this
method −

44
 getopt.getopt(args, options, [long_options])
Here is the detail of the parameters −
 args − This is the argument list to be parsed.
 options − This is the string of option letters that the script wants to recognize, with options that
require an argument should be followed by a colon (:).
 long_options − This is optional parameter and if specified, must be a list of strings with the names
of the long options, which should be supported. Long options, which require an argument should be
followed by an equal sign ('='). To accept only long options, options should be an empty string.
 This method getopt.getopt() returns value consisting of two elements: the first is a list of (option,
value) pairs. The second is the list of program arguments left after the option list was stripped. Each
option-and-value pair returned has the option as its first element, prefixed with a hyphen for short
options (e.g., '-x') or two hyphens for long options (e.g., '--long-option').
Example
 Following is a Python program which takes three arguments at command line:
 First command line argument is -h which will be used to display the usage help of the program.
 Second argument is either -i or --ifile which we are considering as input file.
 Third argument is either -o or --ofile which we are considering as output file.
 In Python, you can access command line arguments using the sys module or the more powerful
argparse module.
 The sys.argv variable is a list in the sys module that contains the command-line arguments passed to
the script.
 However, the argparse module is more flexible and provides a way to define and handle command-
line arguments in a structured manner.
Using sys.argv:
import sys
# The first element in sys.argv is the script name itself
script_name = sys.argv[0]
# The rest of the elements are the command-line arguments
arguments = sys.argv[1:]
print(f"Script Name: {script_name}")
print(f"Arguments: {arguments}")
When you run a script with command line arguments, like this:

45
Using argparse:
 The argparse module provides a more sophisticated way to handle command-line arguments,
allowing you to define options, positional arguments, and more.
 argparse allows you to define various argument types, specify default values, and generate help
messages, making it a powerful tool for handling command-line arguments in a structured and user-
friendly way.

UNIT – III – COMPLETED

STAFF SIGN WITH DATE

46

You might also like