4.file Operation, Pickle & Dictionary
4.file Operation, Pickle & Dictionary
Dictionary
Computer Science & Engineering Department
The Chinese University of Hong Kong
>>>int(‘36’)
36
>>>float(‘36’)
36.0
>>>eval(‘36’)
36
>>>eval(‘2+3*6’)
20
>>> f = open(‘message.txt‘)
>>> for line in f:
... print (line)
try:
f = open('input.txt')
except IOError as e:
print ('unable to open the file with error: "{}"'.format(e.args[-1]))
else:
print ('continue with processing')
f.close()
print ('continue')
>>> unable to open the file with error: "No such file or directory"
continue
CSCI2040 INTRODUCTION TO PYTHON 13
Handling files
• A better way is using with
• Ensure file is closed when the block inside with is exited
>>> import os
>>> os.remove("gone.txt") # removing file
import sys
print ('argument of program are ', sys.argv)
>>>argument of program are
['D:/shor/COURSE/2040/lab/lab3/lab3.py']
29
LEGB
• L: local
• E: Enclosing function definitions
• G: Global
• B: built-in functions
• When Python is looking for meaning attached to a name, it
search the scope in the order: Local, Enclosing, Global, Built-in
>>> x = 42
>>> def afun():
...
...
x = 12
print (x)
Only creating local var
>>> afun()
12
>>> print (x)
42 30
Enclosing
• Occurs when one function is defined inside another
• Each function definition creates a new scope for variables at that level
33
dir function
• dir can be used to access a list of names in current scope
• Get global scope in topmost level
>>> z = 12
>>> def dirTest():
... x = 34
... print (dir())
>>> print (dir())
['__builtins__', '__doc__', '__name__', '__package__',
'dirTest', 'pywin', 'z']
>>> dirTest()
['x']
34
dir function
• Can accept an argument
• Return scope of the object