CBSE CS and IP

CBSE Class 11 & 12 Computer Science and Informatics Practices Python Materials, Video Lecture

Showing posts with label Class 12 CS. Show all posts
Showing posts with label Class 12 CS. Show all posts

File Handling in Python - an Introduction

File Handling in Python - an Introduction

What is a file?

  • Every file in the computer is just a series of bytes, which is arranged one after the other.
  • All the bytes are of 8 bits, Hence each byte is a number between 0 and 255.
  • As we discussed in the above point, every file consists of bytes. So, each file can be considered as a binary file.  
  • But if the file contains bytes for only text (characters, numbers, and other symbols) that everyone uses for general purpose, then the file can be considered as a text file.

Types of Files

Binary Files – A binary file is just a file that contains information in the same format in which the
information is held in memory.

Text Files - Text files can be considered as a subset of binary files. That is used to store human-readable characters as RTF (rich text file) or plain text document. Text files are of two types:-
  • Plain text files (.txt)
  • Rich text files (.rtf)
CSV Files (Comma Separated Values) – A Comma Separated Values (CSV) file is a simple text file that contains data as comma-separated values. CSV files can be used for exporting and importing the data between different applications. For example, we can transfer data between databases and Python Pandas using CSV. 



Absolute and Relative Path of Files

Absolute Path – It is a full path of the file from the root directory.
Ex : - C:\Users\Tanmay\Desktop\Delete\file handling.txt

Relative Path – It is the path of the file from the current working directory.
Ex: -If I am on Desktop then the relative Path for file “file handling.txt” is .\Delete\file handling.txt

Operation on files in python

1.Opening a file– open() function
2.Read/Write file–
                 – Read Functions – read() , readline(), readlines()
                 – Write Functions – write() , writelines()
3.Close the File – close() Function
4.Remove the file – remove() Function of OS Module

Read the contents of an existing file

1.Open the file– 
file_object = open(“read_sample.txt”, ’r’) # Relative Path
file_object = open(“C:\Desktop\Notes\sample.txt”) #Absolute Path

2.Reading the file– 
rf = file_object.read()
print(rf)

3.Closing the file– 
file_object.close()




STANDARD INPUT ,OUTPUT AND ERROR STREAMS

Standard Streams: stdin, stdout, stderr:

Standard Streams:

  • stdin: Standard Input Device (Ex. Reading from Keyboa
  • Stdout: Standard Output Device (Ex. Printing on Monitor)
  • Stderr: Same as stdout but normally only for errors.

Internally these standard devices are implemented as files called
Standard Streams. These are available in sys Module.

After importing sys Module we can use these Standard Streams in
the same way you use other files.


import sys

  • sys.stdin.read() – let you read from keyboard
  • sys.stdout.write() – let you write of the standard output Device
  • sys.stderr.write() – let you write the error

When we start python these files opened in:
  • stdin(read mode)
  • stout(write mode)
  • stderr(write mode)

Sample Program - 1

Sample Program - 2





VARIABLES AND MEMORY ALLOCATION IN PYTHON

VARIABLES AND  MEMORY ALLOCATION IN PYTHON

Variables and memory addresses in Python

Variable are Objects in Python:-

Python’s variables are not storage containers, rather Python variables are like memory references, they refer to the memory address where the value is stored.

Mutability/Immutability of data type:-

        Mutable Type                                                                                   Immutable Type
If the variable is referring to                                                              If the variable is referring to
mutable type, then any                                                                       immutable type, then any
changes in its value will not                                                              changes in its value will also
change the memory address                                                            change the memory address
of the variable.                                                                                     it is referring to.

Ex:- list, dictionary,                                                                            Ex:- int, float, decimal,
set and user-defined                                                                          bool, string, tuple, and
classes.                                                                                                range.

Interesting Facts:-

Python keeps integers from -5 to 256 as an array in memory. If you are using any object
that is referring to any of these int type numbers will use these stored numbers.





SCOPE OF AN OBJECT IN PYTHON

Variable scope in Python

Scope Definition

Part of the program within which a name is legal and accessible is called the scope of name. All variables in Python are objects. So in this post, we are considering Variables in place of Objects. 

To understand the scope of variables, let us discuss the following example:

# CASE - 1
var = 9
def fun():
    print("inside :", var)  ## inside : 9
fun()    
print("Outside :" ,var)     ## Outside : 9


# CASE - 2
var = 9
def fun():
    var = 10
    print("inside :", var)  ## inside : 10
fun()    
print("Outside :" ,var)     ## Outside : 9


In the above example, there are two cases. In CASE-1, var is declared outside the function fun(). In CASE-2, two var are declared, one inside the fun() and second outside the fun()

If you compare the output in both CASES, you will find that in CASE-2, the value of var is taken from inside the function. But, in the case of CASE-1, the value of var was taken from outside the function, because there was no Local variable var was available.

So, this is called the scope of variables. First, the variable will be searched from within the function. Then if Local Variable is not available then python will search the variable outside the function.

In the CASE-2, the value of var was changed to 10 inside the function. But, it did not affect the value of var outside the function. Because a new copy of var was created inside the function. When the python control came out of the function the variable var (which was created inside the function) got destroyed. That is why the value of var outside the function displayed 9.     

Types of Variables with respect to its Scope

There are three types of variables in respect of Scope:
  1. Local Variable
  2. Global Variable
  3. Non-Local Variable
Let us now discuss each type of variable one by one.

  1. Local Variable: Local variable is a variable, which is defined inside a block (ex:- a Function) and cannot be accessible outside that block.

    In the following example, Y is a local variable to function foo().
    # variable y is a local variable
    
    def foo():
        y = "local 19"
        print(y)       ##Output: local 9
    foo()
    
    

  2. Global Variable: In Python, a variable declared outside of the function or in global scope is known as a global variable. This means that a global variable can be accessed from inside and outside of the function.
    # Here X is a Global Variable
    
    X = "Global"
    def foo():
        print("X Inside:", X)   ## X Inside: Global
    
    foo()
    print("X Outside:", X)      ## X Outside: Global
    
    

    In the above example, 'X' is a Global Variable. It is accessible within the foo() and outside the foo(). That means 'X' is accessible from throughout the program.

    Using Local and Global Variables Together:

    # Using global and local variable togather with same name
    
    def foo():
        X = 10
        print("Local X:", X)  ## Local X: 10
    foo()
    print("Global X:", X)  ## NameError: name 'X' is not defined
    
    
    

    From the above example, you can understand if we define a variable inside a function and try to access it from outside the function, we will get the error 'X' is not defined. Because once the control comes out of the function foo() all the variables declared inside the function get destroyed.

    Global Keyword:

    When we declare the variable outside the function and try to change it from within the function, it will not change the value. To change the Global value from inside a function we will use the global keyword.

    ## Without 'global keyword'
    X = "Global"
    def foo():
        X = 'Local'
        print("X Inside:", X)   ## X Inside: Local
    
    foo()
    print("X Outside:", X)      ## X Outside: Global
    
    
    ## With 'global keyword'
    X = "Global"
    def foo():
        global X
        X = 'Local'
        print("X Inside:", X)   ## X Inside: Local
    
    foo()
    print("X Outside:", X)      ## X Outside: Local
    
    

  3. Non-Local Variable: Nonlocal Variable is used in a nested function whose local scope is not defined. This means that the variable can be neither in the local nor the global scope.

    We can understand the working of a non-local variable by the following example.

    # variable x is working as Global,Local and NonLocal
    
    1. x = "Global"
    2. def outer():
    3.    x = "local"
    4.    def inner():
    5.        nonlocal x
    6.        x = "nonlocal"
    7.        print("inner:", x) ## inner: nonlocal
    8.    inner()
    9.    print("outer:", x)   ## outer: nonlocal
    10.
    11. outer()
    12. print(x)          ## Global
    
    

    In the above example, at line 1 we have declared a variable x with values as "Global". Then there are two functions outer() and inner(). In both the functions, we have declared two variables with values "local" (line 3) and "nonlocal"(line 6). All the variables are having same name 'x'.

    which is declared at line 5, I am using a keyword nonlocal x this is telling the python to use the variable x which is just one scope above i.e. variable x of the outer() function. So, instead of creating its own copy of 'x' outer inner() will use the variable of the outer() function.

    That is why at line 7 and line 9, both are having the value of 'x' as nonlocal. At line 12, value is coming from Global Variable 'x' which is declared at line 1.

CSV (Comma Separated Values) Handling in Python

CSV File Handling in Python


What is CSV File

  • A Comma Separated Values (CSV) file is a plain text file that contains the comma-separated data.
  • These files are often used for exchanging data between different applications.
  • CSV files are usually created by programs that handle huge amounts of data. They are used to export data from spreadsheets (ex:- excel file) and databases (Ex:- Oracle, MySQL). It can be used to import data into a spreadsheet or a database.


CSV File Structure


## sample.csv file structure

Name, DOB, City
Ram, 12-Jul-2001, Delhi
Mohan, 23-Jan-2005, Delhi
Suraj, 17-Dec-2002, Kolkata


Python CSV module

  • CSV Module is available in Python Standard Library.
  • The CSV module contains classes that are used to read and write tabular form of data into CSV format.
  • To work with CSV Files, programmer have to import CSV Module.

import csv

Methods of CSV Module :
  • writer( ) 
  • reader( )
Both the methods return an Object of writer or reader class. Writer Object again have two methods  – writerow( ) , writerows( ).

writer( ) Methods

This function returns a writer object which is used for converting the data given by the user into delimited strings on the file object.
W_obj = csv.writer(csvfile, quotechar='"', delimiter=',',
lineterminator='\r\n', quoting=csv.QUOTE_MINIMAL )



writer( ) Object Methods –

  • w_obj . writerow( <Sequence> ) : Write a Single Line
  • w_obj . writerows ( <Nested Sequence> ) : Write Multiple Lines
    Example:-
    ## writerow()
    import csv
    row=['Nikhil', 'CEO', '2', '9.0']
    f=open("myfile.csv", 'w')
    w_obj = csv.writer(f)
    w_obj.writerow(row)
    f.close()
    
    
    ## writerows()
    import csv
    rows = [['Nikhil','CEO','2','9.0'],
            ['Sanchit','CEO','2','9.1']]
    f=open("myfile.csv",'w')
    w_obj = csv.writer(f)
    w_obj.writerows(rows)
    f.close()
    
    

reader( ) Methods

This function returns a reader object which will be used to iterate over lines of a given CSV file.
r_obj = csv.reader( csvfile_obj )

To access each row, we have to iterate over this Object.
for i in r_obj:
    print(i)

Example:-
import csv
f=open("myfile.csv",'r')
r_obj = csv.reader(f)
for data in r_obj:
    print(data)
f.close()


If we consider the sample.csv file given above in the CSV file structure the output of the above code will be:
## OUTPUT

['Name', 'DOB', 'City']
['Ram', '12-Jul-2001', 'Delhi']
['Mohan', '23-Jan-2005', 'Delhi']
['Suraj', '17-Dec-2002', 'Kolkata']


Problem with writer( ) and Solution

  • Extra Newline after each line in CSV File.
  • To remove this we have to Open the CSV File with newline Parameter as Empty '' string:
    f=open("myfile.csv", 'w', newline = '')
  • New Code:
  • import csv
    row=['Nikhil', 'CEO', '2', '9.0']
    f=open("myfile.csv", 'w', newline = '')
    w_obj = csv.writer(f)
    w_obj.writerow(row)
    f.close()
    
    

Why Problem with the writer( )


Universal Newline
'\r' Carriage Return Mac OS
'\n' Line Feed Unix
'\r\n' Carriage Return + New Line MS-DOS, Windows

  • since the CSV module does its own (universal) newline handling. writer() has default line terminator parameter is '\r\n'. When we do not Open the file with newline=''(Empty) python replaces '\r' to '\n'.
  • So the newline end will become '\n\n'. That’s why there is an extra newline that will come in CSV.
Ref:-