COMP10001 Lecture 15: Modules and files week 5b

58 views3 pages
Modules and files week 5b/c (Lec 14/15)
Modules are pre-prepared “stores” of convenient methods/variables
which expand the functionality of Python
To access the contents of a module, import it
o import math
o import adds the module to the local namespace, which cannot be
called globally
o for example
because “pi” is imported locally to the function “area”, it
could not be called outside the function by print
local variables - radius, pi
global variables - area
It is also possible, (but generally avoided) to import all methods and
constants from a library into the local namespace
o from math import *
o area = pi * radius**2
Instead you can selectively import objects:
o from math import pi,e
o area = pi * radius**2
Files
Reading files
o Reading data in from a (local) file:
FILENAME = ‘jabberwocky.txt’
text = open(FILENAME).read( )
lines = open(FILENAME).readlines( )
for line in file:
…...
o read( ) reads the entire file
o readlines( ) reads into a list of lines
Unlock document

This preview shows page 1 of the document.
Unlock all 3 pages and 3 million more documents.

Already have an account? Log in

Document Summary

It is also possible, (but generally avoided) to import all methods and constants from a library into the local namespace: from math import , area = pi * radius**2. Instead you can selectively import objects: from math import pi,e, area = pi * radius**2. W" means to write - use w" over an existing file would overwrite the original one text. write ( ") text. close( : appending to a file, filename = file. txt" text = open(filename, a") text. write( ") text. close( ) A" means to append - add new lines to the original file: when using dictionaries as accumulators you need to initialise every value for new keys , or use defaultdict, without defaultdict. List comprehensions: we are often constructing lists in python using for loops, e. g. list comprehensions allow us to do this in a single line, produces the same result of the last program.

Get access

Grade+20% off
$8 USD/m$10 USD/m
Billed $96 USD annually
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
40 Verified Answers
Class+
$8 USD/m
Billed $96 USD annually
Class+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
30 Verified Answers

Related Documents