0% found this document useful (0 votes)
16 views

python_classes_filesetc

Uploaded by

ranganadh
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

python_classes_filesetc

Uploaded by

ranganadh
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 26

Python Classes/Objects

-----------------------
Python is an object oriented programming language.

Almost everything in Python is an object, with its properties and methods.

A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class
---------------
To create a class, use the keyword class:

Create a class named MyClass, with a property named x:

class MyClass:
x = 5

Create Object
--------------
Now we can use the class named MyClass to create objects:

Example
Create an object named p1, and print the value of x:

p1 = MyClass()
print(p1.x)

The __init__() Function


------------------------
The examples above are classes and objects in their simplest form, and are not
really useful in real life applications.

To understand the meaning of classes we have to understand the built-in __init__()


function.

All classes have a function called __init__(), which is always executed when the
class is being initiated.

Use the __init__() function to assign values to object properties, or other


operations that are necessary to do when the object is being created:

Example
--------
Create a class named Person, use the __init__() function to assign values for name
and age:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)

Note: The __init__() function is called automatically every time the class is being
used to create a new object.
The __str__() Function
-----------------------
The __str__() function controls what should be returned when the class object is
represented as a string.

If the __str__() function is not set, the string representation of the object is
returned:

Example
--------
The string representation of an object WITHOUT the __str__() function:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person("John", 36)

print(p1)

The string representation of an object WITH the __str__() function:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def __str__(self):
return f"{self.name}({self.age})"

p1 = Person("John", 36)

print(p1)

Object Methods
---------------
Objects can also contain methods. Methods in objects are functions that belong to
the object.

Let us create a method in the Person class:

Example
-------
Insert a function that prints a greeting, and execute it on the p1 object:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()

The self Parameter


------------------
The self parameter is a reference to the current instance of the class, and is used
to access variables that belongs to the class.

It does not have to be named self , you can call it whatever you like, but it has
to be the first parameter of any function in the class:

Example
--------
Use the words mysillyobject and abc instead of self:

class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age

def myfunc(abc):
print("Hello my name is " + abc.name)

p1 = Person("John", 36)
p1.myfunc()

Modify Object Properties


-------------------------
You can modify properties on objects like this:

Example
-------
Set the age of p1 to 40:

p1.age = 40

Delete Object Properties


------------------------
You can delete properties on objects by using the del keyword:

Example
--------
Delete the age property from the p1 object:

del p1.age

Delete Objects
--------------
You can delete objects by using the del keyword:

Example
-------
Delete the p1 object:

del p1

The pass Statement


------------------
class definitions cannot be empty, but if you for some reason have a class
definition with no content, put in the pass statement to avoid getting an error.

Example
-------
class Person:
pass

Python Inheritance
-------------------
Inheritance allows us to define a class that inherits all the methods and
properties from another class.

Parent class is the class being inherited from, also called base class.

Child class is the class that inherits from another class, also called derived
class.

Create a Parent Class


----------------------
Any class can be a parent class, so the syntax is the same as creating any other
class:

Create a class named Person, with firstname and lastname properties, and a
printname method:

class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname

def printname(self):
print(self.firstname, self.lastname)

#Use the Person class to create an object, and then execute the printname method:

x = Person("John", "Doe")
x.printname()

Create a Child Class


---------------------
To create a class that inherits the functionality from another class, send the
parent class as a parameter when creating the child class:

Example
Create a class named Student, which will inherit the properties and methods from
the Person class:

class Student(Person):
pass

Note: Use the pass keyword when you do not want to add any other properties or
methods to the class.

Now the Student class has the same properties and methods as the Person class.

Example
--------
Use the Student class to create an object, and then execute the printname method:

x = Student("Mike", "Olsen")
x.printname()

Add the __init__() Function


-----------------------------
So far we have created a child class that inherits the properties and methods from
its parent.

We want to add the __init__() function to the child class (instead of the pass
keyword).

Note: The __init__() function is called automatically every time the class is being
used to create a new object.

Example
Add the __init__() function to the Student class:

class Student(Person):
def __init__(self, fname, lname):
#add properties etc.

When you add the __init__() function, the child class will no longer inherit the
parent's __init__() function.

Note: The child's __init__() function overrides the inheritance of the parent's
__init__() function.

To keep the inheritance of the parent's __init__() function, add a call to the
parent's __init__() function:

Example
-------
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)

Now we have successfully added the __init__() function, and kept the inheritance of
the parent class, and we are ready to add functionality in the __init__() function.

Use the super() Function


------------------------
Python also has a super() function that will make the child class inherit all the
methods and properties from its parent:

Example
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)

Add Properties
---------------
Example
Add a property called graduationyear to the Student class:

class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
self.graduationyear = 2019

In the example below, the year 2019 should be a variable, and passed into the
Student class when creating student objects. To do so, add another parameter in the
__init__() function:
Example
-------
Add a year parameter, and pass the correct year when creating objects:

class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year

x = Student("Mike", "Olsen", 2019)

Add Methods
-------------
Example
-------
Add a method called welcome to the Student class:

class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year

def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of",
self.graduationyear)

Python Iterators
----------------
An iterator is an object that contains a countable number of values.

An iterator is an object that can be iterated upon, meaning that you can traverse
through all the values.

Technically, in Python, an iterator is an object which implements the iterator


protocol, which consist of the methods __iter__() and __next__().

Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable
containers which you can get an iterator from.

All these objects have a iter() method which is used to get an iterator:

Example
-------
Return an iterator from a tuple, and print each value:

mytuple = ("apple", "banana", "cherry")


myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))

Example
-------
Strings are also iterable objects, containing a sequence of characters:

mystr = "banana"
myit = iter(mystr)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))

Looping Through an Iterator


----------------------------
We can also use a for loop to iterate through an iterable object:

Example
-------
Iterate the values of a tuple:

mytuple = ("apple", "banana", "cherry")

for x in mytuple:
print(x)

Example
--------
Iterate the characters of a string:

mystr = "banana"

for x in mystr:
print(x)

Example
--------
Create an iterator that returns numbers, starting with 1, and each sequence will
increase by one (returning 1,2,3,4,5 etc.):

class MyNumbers:
def __iter__(self):
self.a = 1
return self

def __next__(self):
x = self.a
self.a += 1
return x

myclass = MyNumbers()
myiter = iter(myclass)

print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))

Python Polymorphism
--------------------
The word "polymorphism" means "many forms", and in programming it refers to
methods/functions/operators with the same name that can be executed on many objects
or classes.
Function Polymorphism
---------------------
An example of a Python function that can be used on different objects is the len()
function.

String
------
For strings len() returns the number of characters:

Example
-------
x = "Hello World!"

print(len(x))

Tuple
-----
For tuples len() returns the number of items in the tuple:

Example
-------
mytuple = ("apple", "banana", "cherry")

print(len(mytuple))

Dictionary
----------
For dictionaries len() returns the number of key/value pairs in the dictionary:

Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

print(len(thisdict))

Class Polymorphism
-------------------
Polymorphism is often used in Class methods, where we can have multiple classes
with the same method name.

For example, say we have three classes: Car, Boat, and Plane, and they all have a
method called move():

Example
-------
Different classes with the same method:

class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model

def move(self):
print("Drive!")

class Boat:
def __init__(self, brand, model):
self.brand = brand
self.model = model

def move(self):
print("Sail!")

class Plane:
def __init__(self, brand, model):
self.brand = brand
self.model = model

def move(self):
print("Fly!")

car1 = Car("Ford", "Mustang") #Create a Car class


boat1 = Boat("Ibiza", "Touring 20") #Create a Boat class
plane1 = Plane("Boeing", "747") #Create a Plane class

for x in (car1, boat1, plane1):


x.move()

Inheritance Class Polymorphism


------------------------------
What about classes with child classes with the same name? Can we use polymorphism
there?

Yes. If we use the example above and make a parent class called Vehicle, and make
Car, Boat, Plane child classes of Vehicle, the child classes inherits the Vehicle
methods, but can override them:

Example
-------
Create a class called Vehicle and make Car, Boat, Plane child classes of Vehicle:

class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model

def move(self):
print("Move!")

class Car(Vehicle):
pass

class Boat(Vehicle):
def move(self):
print("Sail!")

class Plane(Vehicle):
def move(self):
print("Fly!")

car1 = Car("Ford", "Mustang") #Create a Car object


boat1 = Boat("Ibiza", "Touring 20") #Create a Boat object
plane1 = Plane("Boeing", "747") #Create a Plane object

for x in (car1, boat1, plane1):


print(x.brand)
print(x.model)
x.move()

Child classes inherits the properties and methods from the parent class.

In the example above you can see that the Car class is empty, but it inherits
brand, model, and move() from Vehicle.

The Boat and Plane classes also inherit brand, model, and move() from Vehicle, but
they both override the move() method.

Because of polymorphism we can execute the same method for all classes.

Python Scope
-------------
A variable is only available from inside the region it is created. This is called
scope.

Local Scope
-----------
A variable created inside a function belongs to the local scope of that function,
and can only be used inside that function.

Example
--------
A variable created inside a function is available inside that function:

def myfunc():
x = 300
print(x)

myfunc()

Function Inside Function


-------------------------
As explained in the example above, the variable x is not available outside the
function, but it is available for any function inside the function:

Example
-------
The local variable can be accessed from a function within the function:

def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()

myfunc()

Global Scope
-------------
A variable created in the main body of the Python code is a global variable and
belongs to the global scope.

Global variables are available from within any scope, global and local.

Example
--------
A variable created outside of a function is global and can be used by anyone:

x = 300

def myfunc():
print(x)

myfunc()

print(x)

Naming Variables
-----------------
If you operate with the same variable name inside and outside of a function, Python
will treat them as two separate variables, one available in the global scope
(outside the function) and one available in the local scope (inside the function):

Example
-------
The function will print the local x, and then the code will print the global x:

x = 300

def myfunc():
x = 200
print(x)

myfunc()
print(x)

Global Keyword
--------------
If you need to create a global variable, but are stuck in the local scope, you can
use the global keyword.

The global keyword makes the variable global.

Example
--------
If you use the global keyword, the variable belongs to the global scope:

def myfunc():
global x
x = 300

myfunc()

print(x)

Also, use the global keyword if you want to make a change to a global variable
inside a function.

Example
-------
To change the value of a global variable inside a function, refer to the variable
by using the global keyword:
x = 300

def myfunc():
global x
x = 200

myfunc()

print(x)

Nonlocal Keyword
----------------
The nonlocal keyword is used to work with variables inside nested functions.

The nonlocal keyword makes the variable belong to the outer function.

Example
-------
If you use the nonlocal keyword, the variable will belong to the outer function:

def myfunc1():
x = "Jane"
def myfunc2():
nonlocal x
x = "hello"
myfunc2()
return x

print(myfunc1())

Python Modules
---------------
What is a Module?
Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your application.

Create a Module
----------------
To create a module just save the code you want in a file with the file
extension .py:

Example
-------
Save this code in a file named mymodule.py

def greeting(name):
print("Hello, " + name)

Use a Module
------------
Now we can use the module we just created, by using the import statement:

Example
Import the module named mymodule, and call the greeting function:

import mymodule

mymodule.greeting("Ranganadh")
Variables in Module
-------------------
The module can contain functions, as already described, but also variables of all
types (arrays, dictionaries, objects etc):

Example
-------
Save this code in the file mymodule.py

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example
--------
Import the module named mymodule, and access the person1 dictionary:

import mymodule

a = mymodule.person1["age"]
print(a)

Naming a Module
---------------
You can name the module file whatever you like, but it must have the file extension
.py

Re-naming a Module
-------------------
You can create an alias when you import a module, by using the as keyword:

Example
--------
Create an alias for mymodule called mx:

import mymodule as mx

a = mx.person1["age"]
print(a)

Built-in Modules
----------------
There are several built-in modules in Python, which you can import whenever you
like.

Example
-------
Import and use the platform module:

import platform

x = platform.system()
print(x)

Using the dir() Function


------------------------
There is a built-in function to list all the function names (or variable names) in
a module. The dir() function:

Example
--------
List all the defined names belonging to the platform module:

import platform

x = dir(platform)
print(x)

Note: The dir() function can be used on all modules, also the ones you create
yourself.

Import From Module


------------------
You can choose to import only parts from a module, by using the from keyword.

Example
--------
The module named mymodule has one function and one dictionary:

def greeting(name):
print("Hello, " + name)

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example
--------
Import only the person1 dictionary from the module:

from mymodule import person1

print (person1["age"])

Note: When importing using the from keyword, do not use the module name when
referring to elements in the module. Example: person1["age"], not
mymodule.person1["age"]

Python Datetime
---------------
Python Dates
------------
A date in Python is not a data type of its own, but we can import a module named
datetime to work with dates as date objects.

Example
-------
Import the datetime module and display the current date:

import datetime

x = datetime.datetime.now()
print(x)

Date Output
-----------
When we execute the code from the example above the result will be:

2024-04-29 11:38:08.036860
The date contains year, month, day, hour, minute, second, and microsecond.

The datetime module has many methods to return information about the date object.

Example
-------
Return the year and name of weekday:

import datetime

x = datetime.datetime.now()

print(x.year)
print(x.strftime("%A"))

Creating Date Objects


---------------------
To create a date, we can use the datetime() class (constructor) of the datetime
module.

The datetime() class requires three parameters to create a date: year, month, day.

Example
-------
Create a date object:

import datetime

x = datetime.datetime(2020, 5, 17)

print(x)

The datetime() class also takes parameters for time and timezone (hour, minute,
second, microsecond, tzone), but they are optional, and has a default value of 0,
(None for timezone).

The strftime() Method


----------------------
The datetime object has a method for formatting date objects into readable strings.

The method is called strftime(), and takes one parameter, format, to specify the
format of the returned string:

Example
=======
Display the name of the month:

import datetime

x = datetime.datetime(2018, 6, 1)

print(x.strftime("%B"))
A reference of all the legal format codes:

Directive Description Example


%a Weekday, short version Wed
%A Weekday, full version Wednesday
%w Weekday as a number 0-6, 0 is Sunday 3
%d Day of month 01-31 31
%b Month name, short version Dec
%B Month name, full version December
%m Month as a number 01-12 12
%y Year, short version, without century 18
%Y Year, full version 2024
%H Hour 00-23 17
%I Hour 00-12 05
%p AM/PM PM
%M Minute 00-59 41
%S Second 00-59 08
%f Microsecond 000000-999999 548513
%j Day number of year 001-366 365
%U Week number of year, Sunday as the first day of week, 00-5352
%W Week number of year, Monday as the first day of week, 00-5352
%c Local version of date and time Mon Dec 31 17:41:00 2018
%C Century 20
%x Local version of date 12/31/24
%X Local version of time 17:41:00

Python Math
------------
Python has a set of built-in math functions, including an extensive math module,
that allows you to perform mathematical tasks on numbers.

Built-in Math Functions


------------------------
The min() and max() functions can be used to find the lowest or highest value in an
iterable:

Example
-------
x = min(5, 10, 25)
y = max(5, 10, 25)

print(x)
print(y)

The abs() function returns the absolute (positive) value of the specified number:

Example
--------
x = abs(-7.25)

print(x)

The pow(x, y) function returns the value of x to the power of y (xy).

Example
-------
Return the value of 4 to the power of 3 (same as 4 * 4 * 4):
x = pow(4, 3)

print(x)

The Math Module


---------------
Python has also a built-in module called math, which extends the list of
mathematical functions.

To use it, you must import the math module:

import math
When you have imported the math module, you can start using methods and constants
of the module.

The math.sqrt() method for example, returns the square root of a number:

Example
import math

x = math.sqrt(64)

print(x)

The math.ceil() method rounds a number upwards to its nearest integer, and the
math.floor() method rounds a number downwards to its nearest integer, and returns
the result:

Example
--------
import math

x = math.ceil(1.4)
y = math.floor(1.4)

print(x) # returns 2
print(y) # returns 1

The math.pi constant, returns the value of PI (3.14...):

Example
-------
import math

x = math.pi

print(x)

Math Methods
--------------
Method Description
math.ceil() Rounds a number up to the nearest integer
math.comb() Returns the number of ways to choose k items from n items
without repetition and order
math.exp() Returns E raised to the power of x
math.fabs() Returns the absolute value of a number
math.factorial() Returns the factorial of a number
math.floor() Rounds a number down to the nearest integer
math.fmod() Returns the remainder of x/y
math.gcd() Returns the greatest common divisor of two integers
math.isnan() Checks whether a value is NaN (not a number) or not
math.isqrt() Rounds a square root number downwards to the nearest integer
math.log() Returns the natural logarithm of a number, or the logarithm of number
to base
math.log10() Returns the base-10 logarithm of x
math.pow() Returns the value of x to the power of y
math.remainder() Returns the closest value that can make numerator
completely divisible by the denominator
math.sqrt() Returns the square root of a number
math.trunc() Returns the truncated integer parts of a number

Math Constants
---------------
Constant Description
math.e Returns Euler's number (2.7182...)
math.pi Returns PI (3.1415...)
math.tau Returns tau (6.2831...)

Python statistics Module


-------------------------
Python has a built-in module that you can use to calculate mathematical statistics
of numeric data.

The statistics module was new in Python 3.4.

Statistics Methods
-------------------
Method Description
statistics.mean() Calculates the mean (average) of the given data

Example
--------
Calculate the average of the given data:

# Import statistics Library


import statistics

# Calculate average values


print(statistics.mean([1, 3, 5, 7, 9, 11, 13]))
print(statistics.mean([1, 3, 5, 7, 9, 11]))
print(statistics.mean([-11, 5.5, -3.4, 7.1, -9, 22]))

statistics.median() Calculates the median (middle value) of the given data

Example
Calculate the median (middle value) of the given data:

# Import statistics Library


import statistics

# Calculate middle values


print(statistics.median([1, 3, 5, 7, 9, 11, 13]))
print(statistics.median([1, 3, 5, 7, 9, 11]))
print(statistics.median([-11, 5.5, -3.4, 7.1, -9, 22]))

statistics.stdev() Calculates the standard deviation from a sample of


data
Example
Calculate the standard deviation of the given data:

# Import statistics Library


import statistics

# Calculate the standard deviation from a sample of data


print(statistics.stdev([1, 3, 5, 7, 9, 11]))
print(statistics.stdev([2, 2.5, 1.25, 3.1, 1.75, 2.8]))
print(statistics.stdev([-11, 5.5, -3.4, 7.1]))
print(statistics.stdev([1, 30, 50, 100]))

statistics.variance() Calculates the variance from a sample of data

Example
Calculate the variance from a sample of data:

# Import statistics Library


import statistics

# Calculate the variance from a sample of data


print(statistics.variance([1, 3, 5, 7, 9, 11]))
print(statistics.variance([2, 2.5, 1.25, 3.1, 1.75, 2.8]))
print(statistics.variance([-11, 5.5, -3.4, 7.1]))
print(statistics.variance([1, 30, 50, 100]))

Python File Methods


--------------------
Python has a set of methods available for the file object.

Method Description
close() Closes the file
readline() Returns one line from the file
readlines() Returns a list of lines from the file
seek() Change the file position
tell() Returns the current file position
truncate() Resizes the file to a specified size
write() Writes the specified string to the file
writelines() Writes a list of strings to the file

Python Built-in Exceptions


---------------------------
Built-in Exceptions
-------------------
The table below shows built-in exceptions that are usually raised in Python:

Exception Description
ArithmeticError Raised when an error occurs in numeric calculations
Exception Base class for all exceptions
EOFError Raised when the input() method hits an "end of file" condition
(EOF)
IndentationError Raised when indentation is not correct
IndexError Raised when an index of a sequence does not existValueErrorRaised
when there is a wrong value in a specified data type
ZeroDivisionError Raised when the second operator in a division is zero
Python Try Except
--------------------
The try block lets you test a block of code for errors.

The except block lets you handle the error.

The else block lets you execute code when there is no error.

The finally block lets you execute code, regardless of the result of the try- and
except blocks.

Exception Handling
--------------------
When an error occurs, or exception as we call it, Python will normally stop and
generate an error message.

These exceptions can be handled using the try statement:

Example
-------
The try block will generate an exception, because x is not defined:

try:
print(x)
except:
print("An exception occurred")

Since the try block raises an error, the except block will be executed.

Without the try block, the program will crash and raise an error:

Example
-------
This statement will raise an error, because x is not defined:

print(x)

Many Exceptions
---------------
You can define as many exception blocks as you want, e.g. if you want to execute a
special block of code for a special kind of error:

Example
Print one message if the try block raises a NameError and another for other errors:

try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")

Else
You can use the else keyword to define a block of code to be executed if no errors
were raised:

Example
--------
In this example, the try block does not generate any error:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Finally
The finally block, if specified, will be executed regardless if the try block
raises an error or not.

Example
--------
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
This can be useful to close objects and clean up resources:

Example
--------
Try to open and write to a file that is not writable:

try:
f = open("demofile.txt")
try:
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
except:
print("Something went wrong when opening the file")

The program can continue, without leaving the file object open.

Raise an exception
------------------
As a Python developer you can choose to throw an exception if a condition occurs.

To throw (or raise) an exception, use the raise keyword.

Example
-------
Raise an error and stop the program if x is lower than 0:

x = -1

if x < 0:
raise Exception("Sorry, no numbers below zero")

The raise keyword is used to raise an exception.

You can define what kind of error to raise, and the text to print to the user.

Example
-------
Raise a TypeError if x is not an integer:

x = "hello"

if not type(x) is int:


raise TypeError("Only integers are allowed")

Python PIP
-----------
What is PIP?
PIP is a package manager for Python packages, or modules if you like.

Note: If you have Python version 3.4 or later, PIP is included by default.

What is a Package?
A package contains all the files you need for a module.

Modules are Python code libraries you can include in your project.

Check if PIP is Installed


-------------------------
Navigate your command line to the location of Python's script directory, and type
the following:

Example
-------
Check PIP version:

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip --version

Using a Package
--------------
Once the package is installed, it is ready to use.

Import the "camelcase" package into your project.

Example
Import and use "camelcase":

import camelcase

c = camelcase.CamelCase()

txt = "hello world"

print(c.hump(txt))

Remove a Package
-----------------
Use the uninstall command to remove a package:

Example
Uninstall the package named "camelcase":

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip uninstall


camelcase

List Packages
--------------
Use the list command to list all the packages installed on your system:

Example
List installed packages:

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip list

File Handling
The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

"r" - Read - Default value. Opens a file for reading, error if the file does not
exist

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

"x" - Create - Creates the specified file, returns an error if the file exists

In addition you can specify if the file should be handled as binary or text mode

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)

Syntax
To open a file for reading it is enough to specify the name of the file:

f = open("demofile.txt")
The code above is the same as:

f = open("demofile.txt", "rt")
Because "r" for read, and "t" for text are the default values, you do not need to
specify them.

Note: Make sure the file exists, or else you will get an error.

Open a File on the Server


Assume we have the following file, located in the same folder as Python:

demofile.txt

Hello! Welcome to demofile.txt


This file is for testing purposes.
Good Luck!
To open the file, use the built-in open() function.

The open() function returns a file object, which has a read() method for reading
the content of the file:

ExampleGet your own Python Server


f = open("demofile.txt", "r")
print(f.read())

If the file is located in a different location, you will have to specify the file
path, like this:

Example
Open a file on a different location:

f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())

Read Only Parts of the File


By default the read() method returns the whole text, but you can also specify how
many characters you want to return:

Example
Return the 5 first characters of the file:

f = open("demofile.txt", "r")
print(f.read(5))

Read Lines
You can return one line by using the readline() method:

Example
Read one line of the file:

f = open("demofile.txt", "r")
print(f.readline())

By calling readline() two times, you can read the two first lines:

Example
Read two lines of the file:

f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())

By looping through the lines of the file, you can read the whole file, line by
line:

Example
Loop through the file line by line:

f = open("demofile.txt", "r")
for x in f:
print(x)

Close Files
It is a good practice to always close the file when you are done with it.

Example
Close the file when you are finish with it:

f = open("demofile.txt", "r")
print(f.readline())
f.close()

Write to an Existing File


To write to an existing file, you must add a parameter to the open() function:
"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

ExampleGet your own Python Server


Open the file "demofile2.txt" and append content to the file:

f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:


f = open("demofile2.txt", "r")
print(f.read())

Example
Open the file "demofile3.txt" and overwrite the content:

f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the overwriting:


f = open("demofile3.txt", "r")
print(f.read())

Note: the "w" method will overwrite the entire file.

Create a New File


To create a new file in Python, use the open() method, with one of the following
parameters:

"x" - Create - will create a file, returns an error if the file exist

"a" - Append - will create a file if the specified file does not exist

"w" - Write - will create a file if the specified file does not exist

Example
Create a file called "myfile.txt":

f = open("myfile.txt", "x")
Result: a new empty file is created!

Example
Create a new file if it does not exist:

f = open("myfile.txt", "w")
Delete a File
To delete a file, you must import the OS module, and run its os.remove() function:

ExampleGet your own Python Server


Remove the file "demofile.txt":

import os
os.remove("demofile.txt")
Check if File exist:
To avoid getting an error, you might want to check if the file exists before you
try to delete it:
Example
Check if file exists, then delete it:

import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
Delete Folder
To delete an entire folder, use the os.rmdir() method:

Example
Remove the folder "myfolder":

import os
os.rmdir("myfolder")
Note: You can only remove empty folders.

You might also like