Вы находитесь на странице: 1из 93

FILE

A file or a computer file is a chunk of logically related data or information


which can be used by computer programs. Usually a file is kept on a
permanent storage media, e.g. a hard drive disk. A unique name and path
is used by human users or in programs or scripts to access a file for
reading and modification purposes.

While a program is running, its data is stored in random access memory (RAM).

RAM is fast and inexpensive, but it is also volatile, which means that when the
program ends, or the computer shuts down, data in RAM disappears.

To make data available the next time the computer is turned on and the program is
started, it has to be written to a non-volatile storage medium, such a hard drive,
usb drive, or CD-RW.

Data on non-volatile storage media is stored in named locations on the media


called files. By reading and writing files, programs can save information between
program runs.
Working with files is a lot like working with a notebook.

To use a notebook, it has to be opened. When done, it has to be closed.

While the notebook is open, it can either be read from or written to. In either
case, the notebook holder knows where they are.

They can read the whole notebook in its natural order or they can skip around.
All of this applies to files as well.

To open a file, we specify its name and indicate whether we want to read or
write.
Writing our first file

1 myfile = open("test.txt", "w")


2 myfile.write("My first file written from Python\n")
3 myfile.write("---------------------------------\n")
4 myfile.write("Hello, world!\n")
5 myfile.close()
Opening a file creates what we call a file handle.

In this example, the variable myfile refers to the new handle object.

Our program calls methods on the handle, and this makes changes to the actual file
which is usually located on our disk.

On line 1, the open function takes two arguments. The first is the name of the file,
and the second is the mode. Mode "w" means that we are opening the file for
writing.

With mode "w", if there is no file named test.txt on the disk, it will be created. If
there already is one, it will be replaced by the file we are writing.

To put data in the file we invoke the write method on the handle, shown in lines 2,
3 and 4 above.
In bigger programs, lines 24 will usually be replaced by a loop that writes many
more lines into the file. Closing the file handle (line 5) tells the system that we are
done writing and makes the disk file available for reading by other programs (or
by our own program).
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. This function
converts the expressions you pass it to a string and writes the result to
standard output as follows:

print "Python is really a great language,", "isn't


it?";

This would produce 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:
1.raw_input
2.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):
str = raw_input("Enter your input: ");

print "Received input is : ", str


This would prompt you to enter any string and it would display same
string on the screen. When I typed "Hello Python!", it 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:
str = input("Enter your input: ");

print "Received input is : ", str


This would produce 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]
Until now, you have been reading and writing to the standard input and
output. Now we will see how to play with actual data files.
Python provides basic functions and methods necessary to manipulate
files by default. You can do your 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])
F=open(text.txt,encoding=utf-8)
Paramters detail:
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 ie. 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 will take place. If the
buffering value is 1, line buffering will be performed while accessing a file. If
you specify the buffering value as an integer greater than 1, then buffering
action will be performed with the indicated buffer size. If negative, the buffer
size is the system default(default behavior).
A list of the different modes of opening a file:

Modes Description

r Opens a file for reading only. The file pointer is placed at the beginning
of the file. This is the default mode.
rb 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.
r+ Opens a file for both reading and writing. The file pointer will be at the
beginning of the file.
rb+ Opens a file for both reading and writing in binary format. The file
pointer will be at the beginning of the file.
w 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 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+ 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.
A list of the different modes of opening a file:
wb+ Opens a file for both writing and reading in binary format. Overwrites
the 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 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 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.

a+ Opens a file for both appending and reading. The file pointer is 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.

ab+ Opens a file for both appending and reading in binary format. The file
pointer is 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 atrributes:
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:

Attribute Description
file.closed Returns true if file is closed, false otherwise.
file.mode Returns access mode with which file was opened.
file.name Returns name of the file.
file.softspace Returns false if space explicitly required with print, true
otherwise.
Example:
#!/usr/bin/python
fo = open("foo.txt", "wb") # Open a file
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
This would produce following result:
Name of the file: foo.txt
Closed or not : False
Opening mode : wb
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:
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
fo.close()
This would produce following result:
Name of the file: foo.txt
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:
Syntax:
fileObject.write(string);
Example:
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\r\nYeah its
great!!\r\n");
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!!
file.write(str) Write a string to the file. There is no return value.

file.writelines(sequence) Write a sequence of strings to the file. The


sequence can be any iterable object producing strings, typically a list of
strings.

16
The read() Method:
The read() method read a string from an open file. It is important to note that
Python strings can have binary data and not just text.
Syntax:
fileObject.read([count]);
Here passed parameter is the number of bytes to be read from the opend 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, may be until the end of file.
Example:
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
fo.close()
This would produce following result:
Read String is : Python is
file.next() Returns the next line from the file each time it is being
called.

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

file.readline([size]) Read one entire line from the file. A trailing


newline character is kept in the string.

file.readlines([sizehint]) Read until EOF using readline() and


return a list containing the lines. If the 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.
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 all 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:
import os
os.rename( "test1.txt", "test2.txt" )
The delete() Method:
You can use the delete() method to delete files by supplying the name of the
file to be deleted as the argument.
Syntax:
os.remove(file_name)
Example:
import os
os.remove("test2.txt")
Reading a file line-at-a-time
Now that the file exists on our disk, we can open it, this time for reading, and read all
the lines in the file, one at a time.

This time, the mode argument is "r" for reading:

1 mynewhandle = open("test.txt", "r")

2 while True: # Keep reading forever

3 theline = mynewhandle.readline() # Try to read next line

4 if len(theline) == 0: # If there are no more lines

5 break # leave the loop


6
7 # Now process the line weve just read

8 print(theline, end="")
9
10 mynewhandle.close()
This is a handy pattern for our toolbox. In bigger programs, wed squeeze more extensive
logic into the body of the loop at line 8

for example, if each line of the file contained the name and email address of one of our
friends, perhaps wed split the line into some pieces and call a function to send the friend a
party invitation.

On line 8 we suppress the newline character that print usually appends to our strings. Why?
This is because the string already has its own newline: the readline method in line 3 returns
everything up to and including the newline character.

This also explains the end-of-file detection logic: when there are no more lines to be read
from the file, readline returns an empty string one that does not even have a newline at the
end, hence its length is 0.
Reading the whole file at once
Another way of working with text files is to read the complete contents of the file
into a string, and then to use our string-processing skills to work with the
contents.

Wed normally use this method of processing files if we were not interested in the
line structure of the file. For example, weve seen the split method on strings
which can break a string into words.

So here is how we might count the number of words in a file:

1 f = open("somefile.txt")
2 content = f.read()
3 f.close()
4
5 words = content.split()
6 print("There are {0} words in the file..format(len(words)))

Notice here that we left out the "r" mode in line 1. By default, if we dont supply
the mode, Python opens the file for reading.
Some other os file and directory methods..

os.delete(file_name)
os.mkdir("newdir")
os.chdir("newdir")
os.getcwd()
os.rmdir('dirname')

Complete list at:


http://docs.python.org/library/os.html#files-and-directories
An exception is an event, which occurs during the execution of a
program, that disrupts the normal flow of the program's
instructions.
In general, when a Python script encounters a situation that it can't
cope with, it raises an exception. An exception is a Python object
that represents an error.
When a Python script raises an exception, it must either handle the
exception immediately otherwise it would terminate.

Handling an exception:
If you have some suspicious code that may raise an exception, you
can defend your program by placing the suspicious code in a try:
block. After the try: block, include an except: statement, followed by
a block of code which handles the problem as elegantly as possible.
Here is simple syntax of try....except...else blocks:
Try:
Do you operations here.
except Exception_I:
If there is Exception_I, then execute this block.
except Exception_II:
If there is Exception_II, execute this block.
else:
If there is no exception then execute this block.
Here are few important points above the above mentioned syntax:
A single try statement can have multiple except statements. This is
useful when the try block contains statements that may throw
different types of exceptions.
You can also provide a generic except clause, which handles any
exception. (not recommended since you dont really know what
raised the exception).
After the except clause(s), you can include an else-clause. The code
in the else-block executes if the code in the try: block does not raise
an exception.
The else-block is a good place for code that does not need the try:
block's protection.
Here is simple example which opens a file and writes the content in the file
and comes out gracefully because there is no problem at all:
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or write data
else:
print "Written content in the file successfully
fh.close()
If no exception is raised this will produce following output:
Written content in the file successfully
If an exception is raised this will produce following output:
Error cant find file or write data
PYTHON ERRORS AND BUILT-IN EXCEPTIONS

Python (interpreter) raises exceptions when it encounter errors. For example:


divided by zero. In this article, you will learn about different exceptions that
are built-in in Python.

What is Exception?
An exception is an event, which occurs during the execution of a program that
disrupts the normal flow of the program's instructions. In general, when a Python
script encounters a situation that it cannot cope with, it raises an exception. An
exception is a Python object that represents an error. When a Python script raises an
exception, it must either handle the exception immediately otherwise it terminates
and quits.

Handling an exception
If you have some suspicious code that may raise an exception, you can defend your
program by placing the suspicious code in a try: block. After the try: block, include an
except: statement, followed by a block of code which handles the problem as elegantly
as possible.
Python Built-in Exceptions

Illegal operations can raise exceptions. There are plenty of built-in exceptions in
Python that are raised when corresponding errors occur. We can view all the built-
in exceptions using the local() built-in functions as follows.

>>> locals()['__builtins__']

This will return us a dictionary of built-in exceptions, functions and attributes.


Some of the common built-in exceptions in Python programming along with the
error that cause then are tabulated below.
AssertionError Raised when assert statement fails.

AttributeError Raised when attribute assignment or reference fails.

EOFError Raised when the input() functions hits end-of-file condition.

FloatingPointError Raised when a floating point operation fails.

GeneratorExit Raise when a generator's close() method is called.

ImportError Raised when the imported module is not found.

IndexError Raised when index of a sequence is out of range.

KeyError Raised when a key is not found in a dictionary.

KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or


delete).
MemoryError Raised when an operation runs out of memory.
NameError Raised when a variable is not found in local or global scope.

NotImplementedError Raised by abstract methods.

OSError Raised when system operation causes system related error.

OverflowError Raised when result of an arithmetic operation is too large to be


represented.

ReferenceError Raised when a weak reference proxy is used to access a garbage


collected referent.

RuntimeError Raised when an error does not fall under any other category.
StopIteration Raised by next() function to indicate that there is no further item
to be returned by iterator.

SyntaxError Raised by parser when syntax error is encountered.


IndentationError Raised when there is incorrect indentation.
TabError Raised when indentation consists of inconsistent tabs and spaces.
SystemError Raised when interpreter detects internal error.
SystemExit Raised by sys.exit() function.
Python Exception Handling - Try, Except and Finally

how to handle exceptions in your Python program using try, except and
finally statements. This will motivate you to write clean, readable and
efficient code in Python.
Catching Exceptions in Python
In Python, exceptions can be handled using a try statement.

A critical operation which can raise exception is placed inside the try clause and the
code that handles exception is written in except clause.

It is up to us, what operations we perform once we have caught the exception. Here
is a simple example.

# import module sys to get the type of exception


import sys
randomList = ['a', 0, 2]
for entry in randomList:
try:
print("The entry is", entry)
r = 1/int(entry)
break
except:
print("Oops!",sys.exc_info()[0],"occured.")
print("Next entry.")
print()
print("The reciprocal of",entry,"is",r)
Output

The entry is a
Oops! <class 'ValueError'> occured.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError' > occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5

In this program, we loop until the user enters an integer that has a valid
reciprocal. The portion that can cause exception is placed inside try block.
If no exception occurs, except block is skipped and normal flow continues. But if
any exception occurs, it is caught by the except block.

Here, we print the name of the exception using ex_info() function


inside sys module and ask the user to try again. We can see that the values 'a' and
'1.3' causes ValueError and '0' causes ZeroDivisionError.
Catching Specific Exceptions in Python

In the above example, we did not mention any exception in the except clause.

This is not a good programming practice as it will catch all exceptions and handle
every case in the same way. We can specify which exceptions an except clause will
catch.

A try clause can have any number of except clause to handle them differently but
only one will be executed in case an exception occurs.

We can use a tuple of values to specify multiple exceptions in an except clause


try:
# do something
pass

except ValueError:
# handle ValueError exception
pass

except (TypeError, ZeroDivisionError):


# handle multiple exceptions
# TypeError and ZeroDivisionError
pass

except:
# handle all other exceptions
pass
Raising Exceptions
In Python programming, exceptions are raised when corresponding errors occur at
run time, but we can forcefully raise it using the keyword raise.

We can also optionally pass in value to the exception to clarify why that exception
was raised.
>>> raise KeyboardInterrupt
Traceback (most recent call last):
KeyboardInterrupt
>>> raise MemoryError("This is an argument")
Traceback (most recent call last):
...
MemoryError: This is an argument
>>> try:
... a = int(input("Enter a positive integer: "))
... if a <= 0:
... raise ValueError("That is not a positive number!")
... except ValueError as ve:
... print(ve)
...
Enter a positive integer: -2
That is not a positive number!
try...finally

The try statement in Python can have an optional finally clause. This clause is
executed no matter what, and is generally used to release external resources.

For example, we may be connected to a remote data center through the network or
working with a file or working with a Graphical User Interface (GUI).

In all these circumstances, we must clean up the resource once used, whether it was
successful or not. These actions (closing a file, GUI or disconnecting from network)
are performed in the finally clause to guarantee execution.

Here is an example of file operations to illustrate this.

try:
f = open("test.txt",encoding = 'utf-8')
# perform file operations
finally:
f.close()
This type of construct makes sure the file is closed even if an exception occurs.
The Python sys module provides access to any command-line
arguments via the sys.argv. This serves two purpose:
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.
Consider the following script test.py:
#!/usr/bin/python
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.
print 'Argument List:', str(sys.argv)
Now run above script as follows:
$ python test.py arg1 arg2 arg3
This will produce following output:
Number of arguments: 4 arguments.
Argument List: ['test.py', 'arg1', 'arg2', 'arg3']
Python provides the 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.

http://docs.python.org/library/getopt.html

Another module (which I personally like better than the python


standard library getopt) for parsing the command line is argparse

http://code.google.com/p/argparse/
Command line arguments (sys.argv)
They sys module in Python is one of many available modules of library code.

What is sys.argv?
sys.argv is the list of commandline arguments passed to the Python program. argv
represents all the items that come along via the commandline input, it's basically a
an array holding the command line arguments of our program. Don't forget that the
counting starts at zero (0) not one (1).

How do I use it?

To use it, you will first have to import it (import sys) The first argument, sys.argv[0],
is always the name of the program as it was invoked, and sys.argv[1] is the first
argument you pass to the program.

It's common that you slice the list to access the actual command line argument:
import sys
program_name = sys.argv[0]
arguments = sys.argv[1:]
count = len(arguments)

This is an example on how to read the argument from the command line

import sys
for x in sys.argv:
print "Argument: ", x
len(sys.argv) , checks how many arguments that have been entered.

len(sys.argv) != 2 just checks whether you entered at least two elements

import sys
if len (sys.argv) != 2 :
print "Usage: python ex.py "
sys.exit (1)
To run it,

simple type:
>python ex.py
Argument: ex.py

>python ex.py hello


Argument: ex.py
Argument: hello

>python ex.py hello world


Argument: ex.py
Argument: hello
Argument: world
Collection of stuff in foo.py file
functions, classes, variables
Importing modules:
import re; print re.match("[a-z]+", s)
from re import match; print match("[a-z]+", s)
Import with rename:
import re as regex
from re import match as m
Before Python 2.0:
import re; regex = re; del re
A module allows you to logically organize your Python code.
Grouping related code into a module makes the code easier to
understand and use.
A module is a Python object with arbitrarily named attributes that
you can bind and reference.
Simply, a module is a file consisting of Python code. A module can
define functions, classes, and variables. A module can also include
runnable code.
Example: Here's an example of a simple module named - hello.py

def print_func( par ):


Hello.py prints Hello : and the passed parameter
print "Hello : ", par
return
You can use any Python source file as a module by executing an import
statement in some other Python source file. Import has the following
syntax:
import module1[, module2[,... moduleN]
When the interpreter encounters an import statement, it imports the
module if the module is present in the search path. The search path is a
list of directories that the interpreter searches before importing a module.
To import the module hello.py we created above, put the following
command at the top of a new script test_module.py:

#!/usr/bin/python
import hello # Import the module hello.py
# Now you can call the defined function that module as follows
hello.print_func("Zara")
When executed test_module.py would produce following output:
Hello : Zara
A module is loaded only once, regardless of the number of times it
is imported. This prevents the module execution from happening
over and over again if multiple imports occur.
Python's from statement lets you import specific attributes from a
module into the current namespace:

from modname import name1[, name2[, ... nameN]]

For example, to import the function fibonacci from the module fib,
use the following statement:

from fib import fibonacci

This statement does not import the entire module fib into the
current namespace; it just introduces the item fibonacci from the
module fib into the global symbol table of the importing module.
When you import a module, the Python interpreter searches for the
module in the following sequences:
The current directory.
If the module isn't found, Python then searches each directory in the
shell variable PYTHONPATH.
If all else fails, Python checks the default path. On UNIX, this default
path is normally /usr/local/lib/python/.
The module search path is stored in the system module sys as the sys.path
variable. The sys.path variable contains the current directory,
PYTHONPATH, and the installation-dependent defaults.
The PYTHONPATH is an environment variable, consisting of a list of
directories. The syntax of PYTHONPATH is the same as that of the shell
variable PATH.
Here is a typical PYTHONPATH from a Windows system:
set PYTHONPATH=c:\python20\lib;
And here is a typical PYTHONPATH from a UNIX system:
set PYTHONPATH=/usr/local/lib/python
12.010 Lec P2 11/16/2010 50
There are three common ways of manipulating dates and times in
Python
time : A python low-level standard library module
datetime : Another standard library module
mxDateTime : A popular third-party module (not discussed
but if you have many time related manipulations in your code I
would recommend installing this module).
Examples
import time
import datetime
print "Today is day", time.localtime()[7], "of the current year"
Today is day 310 of the current year
today = datetime.date.today()
print "Today is day", today.timetuple()[7], "of ", today.year
Today is day 310 of 2010
print "Today is day", today.strftime("%j"), "of the current year
Today is day 310 of the current year
Modules are files containing Python definitions and
statements (ex. name.py)
A modules definitions can be imported into other
modules by using import name
The modules name is available as a global variable
value
To access a modules functions, type name.function()
Modules can contain executable statements along with
function definitions
Each module has its own private symbol table used as
the global symbol table by all functions in the module
Modules can import other modules
Each module is imported once per interpreter session
reload(name)
Can import names from a module into the importing
modules symbol table
from mod import m1, m2 (or *)
m1()
python name.py <arguments>
Runs code as if it was imported
Setting _name_ == _main_ the file can be used as a
script and an importable module
The interpreter searches for a file named name.py
Current directory given by variable sys.path
List of directories specified by PYTHONPATH
Default path (in UNIX - .:/usr/local/lib/python)
Script being run should not have the same name as a
standard module or an error will occur when the
module is imported
If files mod.pyc and mod.py are in the same directory,
there is a byte-compiled version of the module mod
The modification time of the version of mod.py used to
create mod.pyc is stored in mod.pyc
Normally, the user does not need to do anything to
create the .pyc file
A compiled .py file is written to the .pyc
No error for failed attempt, .pyc is recognized as invalid
Contents of the .pyc can be shared by different
machines
-O flag generates optimized code and stores it in .pyo files
Only removes assert statements
.pyc files are ignored and .py files are compiled to optimized
bytecode
Passing two OO flags
Can result in malfunctioning programs
_doc_ strings are removed
Same speed when read from .pyc, .pyo, or .py files, .pyo and .pyc
files are loaded faster
Startup time of a script can be reduced by moving its code to a
module and importing the module
Can have a .pyc or .pyo file without having a .py file for the same
module
Module compileall creates .pyc or .pyo files for all modules in a
directory
Python comes with a library of standard modules described in
the Python Library Reference
Some are built into interpreter
>>> import sys
>>> sys.s1
>>>
>>> sys.s1 = c>
c> print Hello
Hello
c>
sys.path determines the interpreterss search path for modules,
with the default path taken from PYTHONPATH
Can be modified with append() (ex. Sys.path.append(SOMEPATH)
Used to find the names a module defines and returns a
sorted list of strings
>>> import mod
>>> dir(mod)
[_name_, m1, m2]
Without arguments, it lists the names currently
defined (variables, modules, functions, etc)
Does not list names of built-in functions and variables
Use _bulltin_to view all built-in functions and variables
dotted module names (ex. a.b)
Submodule b in package a
Saves authors of multi-module packages from worrying about
each others module names
Python searches through sys.path directories for the package
subdirectory
Users of the package can import individual modules from the
package
Ways to import submodules
import sound.effects.echo
from sound.effects import echo
Submodules must be referenced by full name
An ImportError exception is raised when the package cannot be
found
* does not import all submodules from a package
Ensures that the package has been imported, only
importing the names of the submodules defined in the
package
import sound.effects.echo
import sound.effects.surround
from sound.effects import *
Submodules can refer to each other
Surround might use echo module
import echo also loads surround module
import statement first looks in the containing package
before looking in the standard module search path
Absolute imports refer to submodules of sibling packages
sound.filters.vocoder uses echo module
from sound.effects import echo
Can write explicit relative imports
from . import echo
from .. import formats
from ..filters import equalizer
_path_ is a list containing the name of the directory
holding the packages _init_.py
Changing this variable can affect futute searches for
modules and subpackages in the package
Can be used to extend the set of modules in a package
Not often needed
Collection of modules in directory
Must have __init__.py file
May contain subpackages
Import syntax:
from P.Q.M import foo; print foo()
from P.Q import M; print M.foo()
import P.Q.M; print P.Q.M.foo()
import P.Q.M as M; print M.foo() # new
MODULE

A module is a file containing Python definitions and statements intended for use in
other Python programs. There are many Python modules that come with Python as
part of the standard library. We have seen at least two of these already, the turtle
module and the string module.

Random number
We often want to use random numbers in programs, here are a few typical uses: To
play a game of chance where the computer needs to throw some dice, pick a number,
or flip a coin, To shuffle a deck of playing cards randomly,

To allow/make an enemy spaceship appear at a random location and start shooting at


the player,

To simulate possible rainfall when we make a computerized model for estimating the
environmental impact of building a dam, For encrypting banking sessions on the
Internet.
Python provides a module random that helps with tasks like this. You can
look it up using help, but here are the key things well do with it:

1 import random
2
3 # Create a black box object that generates random numbers
4 rng = random.Random()
5
6 dice_throw = rng.randrange(1,7) # Return an int, one of 1,2,3,4,5,6

7 delay_in_seconds = rng.random() * 5.0


The Time Module

As we start to work with more sophisticated algorithms and bigger programs, a


natural concern is is our code efficient? One way to experiment is to time how long
various operations take.

The time module has a function called clock that is recommended for this purpose.
Whenever clock is called, it returns a floating point number representing how many
seconds have elapsed since your program started running.

The way to use it is to call clock and assign the result to a variable, say t0, just before
you start executing the code you want to measure. Then after execution, call clock
again, (this time well save the result in variable t1).

The difference t1-t0 is the time elapsed, and is a measure of how fast your program is
running.
The Math Module :

The math module contains the kinds of mathematical functions youd typically
find on your calculator (sin, cos, sqrt, asin, log, log10) and some mathematical
constants like pi and e:

>>> import math

>>> math.pi # Constant pi 3.141592653589793


>>> math.e # Constant natural log base 2.718281828459045

>>> math.sqrt(2.0) # Square root function 1.4142135623730951


>>> math.radians(90) # Convert 90 degrees to radians 1.5707963267948966

>>> math.sin(math.radians(90)) # Find sin of 90 degrees 1.0


>>> math.asin(1.0) * 2 # Double the arcsin of 1.0 to get pi 3.141592653589793
CREATING YOUR OWN MODULES

All we need to do to create our own modules is to save our script as a file with a .py
extension.
Suppose, for example, this script is saved as a file named seqtools.py:
1 def remove_at(pos, seq):
2 return seq[:pos] + seq[pos+1:]
We can now use our module, both in scripts we write, or in the interactive Python
interpreter.
To do so, we must first import the module.
>>> import seqtools >>> s = "A string!
>>> seqtools.remove_at(4, s)
A sting!

We do not include the .py file extension when importing. Python expects the file
names of Python modules to end in .py, so the file extension is not included in the
import statement.

The use of modules makes it possible to break up very large programs into
manageable sized parts, and to keep related parts together.
Namespaces

A namespace is a collection of identifiers that belong to a module, or to a function,


(and as we will see soon, in classes too).
Generally, we like a namespace to hold related things, e.g. all the math functions, or
all the typical things wed do with random numbers.

Each module has its own namespace, so we can use the same identifier name in
multiple modules without causing an identification problem.

1 # Module1.py
2
3 question = "What is the meaning of Life, the Universe, and Everything?"
4 answer = 42

1 # Module2.py
2
3 question = "What is your quest?"

4 answer = "To seek the holy grail."


We can now import both modules and access question and answer in each:

1 import module1
2 import module2
3
4 print(module1.question)
5 print(module2.question)
6 print(module1.answer)
7 print(module2.answer)

will output the following: What is the meaning of Life, the Universe, and Everything?
What is your quest?
42
To seek the holy grail.
Attributes and the dot operator

Variables defined inside a module are called attributes of the module. Weve seen
that objects have attributes too:

for example, most objects have a __doc__ attribute, some functions have a
__annotations__ attribute.

Attributes are accessed using the dot operator (.).

The question attribute of module1 and module2 is accessed using


module1.question and module2.question.

Modules contain functions as well as attributes, and the dot operator is used to
access them in the same way. s
Three import statement variants

Here are three different ways to import names into the current namespace, and to
use them:
1 import math
2 x = math.sqrt(10)

Here just the single identifier math is added to the current namespace. If you want
to access one of the functions in the module, you need to use the dot notation to get
to it.

Here is a different arrangement:


1 from math import cos, sin, sqrt
2 x = sqrt(10)

The names are added directly to the current namespace, and can be used without
qualification. The name math is not itself imported, so trying to use the qualified
form math.sqrt would give an error.
Then we have a convenient shorthand:

1 from math import * # Import all the identifiers from math,


2 # adding them to the current namespace.
3 x = sqrt(10) # Use them without qualification.

Of these three, the first method is generally preferred, even though it means a little
more typing each time.

Although, we can make things shorter by importing a module under a different


name:
1 >>> import math as m
2 >>> m.pi 3 3.141592653589793

But hey, with nice editors that do auto-completion, and fast fingers, thats a small
price!
Firoze Abdur Rakib
When a problem encounters and unexpected
termination or fault, it is called an exception
When we try and divide by 0 we terminate abnormally.
Exception handling gives us another opportunity to
recover from the abnormality.
Sometimes we might encounter situations from which
we cannot recover like Outofmemory. These are
considered as errors.
Syntax errors, also known as parsing errors, are perhaps the
most common kind of error you encounter while you are
still learning Python.

The parser repeats the offending line and displays a little


arrow pointing at the earliest point in the line where the
error was detected. The error is detected at the token
preceding the arrow. File name and line number are printed
so you know where to look in case the input came from a
script.
Even if a statement or expression is syntactically
correct, it may cause an error when an attempt is made
to execute it. Errors detected during execution are
called exceptions and are not unconditionally fatal.
Most exceptions are not handled by programs,
however, and result in error messages like cannot
divide by zero or cannot concatenate str and int
objects.
It is possible to write programs that handle selected
exceptions. Consider the following, where a user-generated
interruption is signaled by raising the KeyboardInterrupt
exception.

First the 'try' clause is executed until an exception occurs,


in which case the rest of 'try' clause is skipped and the
'except' clause is executed (depending on type of
exception), and execution continues. If an exception occurs
which does not match the exception named in the except
clause, it is passed on to outer try statements; if no handler
is found, it is an unhandled exception and execution stops.
The last except clause (when many are declared) may
omit the exception name(s), to serve as a wildcard.
This makes it very easy to mask a real programming
error. It can also be used to print an error message and
then re-raise the exception.
The try-except statement has an optional else clause,
which, when present, must follow all except clauses. It
is useful for code that must be executed if the try
clause does not raise an exception.
The raise statement allows the programmer to force a
specified exception to occur.

The sole argument to raise indicates the exception to


be raised.
A simpler form of the raise statement allows one to re-
raise the exception (if you dont want to handle it):
Programs may name their own exceptions by creating
a new exception class. These are derived from the
Exception class, either directly or indirectly.

Here, the def__init__() of Exception has been


overridden. The new behavior simply creates the value
attribute.
The try statement has another optional clause which is
intended to define clean-up actions that must be
executed under all circumstances.

A finally clause is executed before leaving the try


statement, whether an exception has occurred or not.
When an exception has occurred in the try clause and
has not been handled by an except clause, it is re-
raised after the finally clause has been executed. The
finally clause is also executed on the way out when
any other clause of the try statement is exited using
break/continue/return.
Some objects define standard clean-up actions to be
undertaken when the object is no longer needed,
regardless of whether or not the operation using the
object succeeded or failed.
The problem with this code is that it leaves the file
open for an indefinite amount of time after the code
has finished executing.
The with statement allows objects like files to be used
in a way that ensures they are always cleaned up
promptly and correctly.
The file object atrributes:
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:

Attribute Description
file.closed Returns true if file is closed, false otherwise.
file.mode Returns access mode with which file was opened.
file.name Returns name of the file.
file.softspace Returns false if space explicitly required with print, true
otherwise.

Вам также может понравиться