DEV Community

Sandeep
Sandeep

Posted on • Updated on

Python Cheat Sheet Part - 4

File Handling
File handling refers to reading or writing data from files. Python provides some functions that allow us to manipulate data in the files.

open() function

var_name = open("file name", "opening mode")
Enter fullscreen mode Exit fullscreen mode

close() function

var_name.close()
Enter fullscreen mode Exit fullscreen mode

read () function
The read functions contains different methods, read(),readline() and readlines()

read() #return one big string
Enter fullscreen mode Exit fullscreen mode

It returns a list of lines

readlines() #returns a list
Enter fullscreen mode Exit fullscreen mode

It returns one line at a time

readline #returns one line at a time
Enter fullscreen mode Exit fullscreen mode

write function
This function writes a sequence of strings to the file.

write() #Used to write a fixed sequence of characters to a file
Enter fullscreen mode Exit fullscreen mode

It is used to write a list of strings

writelines()
Enter fullscreen mode Exit fullscreen mode

append() function
The append function is used to append to the file instead of overwriting it. To append to an existing file, simply open the file in append mode by using 'a' as the second argument of open() as follows:

file = open("Hello.txt", "a")
Enter fullscreen mode Exit fullscreen mode

Exception Handling
An exception is an unusual condition that results in an interruption in the flow of a program.

try and except
A basic try-catch block in python. When the try block throws an error, the control goes to the except block.

try:
    [Statement body block]
    raise Exception()
except Exception as e:
    [Error processing block]
Enter fullscreen mode Exit fullscreen mode

Object Oriented Programming (OOPS)
It is a programming approach that primarily focuses on using objects and classes. The objects can be any real-world entities.

class
The syntax for writing a class in python

class class_name:
    pass #statements
Enter fullscreen mode Exit fullscreen mode

class with a constructor
The syntax for writing a class with the constructor in python

class Example:

    # Default constructor
    def __init__(self):
        self.name = "Example"

    # A method for printing data members
    def print_me(self):
        print(self.name)
Enter fullscreen mode Exit fullscreen mode

Creating an object
Instantiating an object can be done as follows:

<object-name> = <class-name>(<arguments>)
Enter fullscreen mode Exit fullscreen mode

filter function
The filter function allows you to process an iterable and extract those items that satisfy a given condition

filter(function, iterable)
Enter fullscreen mode Exit fullscreen mode

issubclass function
Used to find whether a class is a subclass of a given class or not as follows

issubclass(obj, classinfo) # returns true if obj is a subclass of classinfo
Enter fullscreen mode Exit fullscreen mode

Iterators and Generators
Here are some of the advanced topics of the Python programming language like iterators and generators

Iterator
Used to create an iterator over an iterable

iter_list = iter(['Harry', 'Aakash', 'Rohan']) 
print(next(iter_list)) 
print(next(iter_list)) 
print(next(iter_list))
Enter fullscreen mode Exit fullscreen mode

Generator
Used to generate values on the fly

# A simple generator function
def my_gen():
    n = 1
    print('This is printed first')
    # Generator function contains yield statements
    yield n
    n += 1
    print('This is printed second')
    yield n
    n += 1
    print('This is printed at last')
    yield n
Enter fullscreen mode Exit fullscreen mode

Decorators
Decorators are used to modifying the behavior of a function or a class. They are usually called before the definition of a function you want to decorate.

property Decorator (getter)

@property
def name(self):
    return self.__name
Enter fullscreen mode Exit fullscreen mode

setter Decorator
It is used to set the property 'name'

@name.setter
def name(self, value):
    self.__name=value
Enter fullscreen mode Exit fullscreen mode

deleter Decorator
It is used to delete the property 'name'

@name.deleter #property-name.deleter decorator

def name(self, value):
    print('Deleting..')
    del self.__name
Enter fullscreen mode Exit fullscreen mode

Python cheat sheet part-1

Python cheat sheet part-2

Python cheat sheet part-3

Latest comments (0)