├── 9781484223840.jpg ├── LICENSE.txt ├── README.md ├── contributing.md └── programs ├── calc.py ├── calculator.py ├── command.py ├── dbcreate.py ├── dbupdate.py ├── division.py ├── divisionHandled.py ├── divisionHandledV2.py ├── duckduckgo.py ├── mod1.py ├── mod1.pyc ├── mydatabase.db ├── people.py ├── people.pyc ├── re.py ├── remail.py ├── test1.py ├── test2.py ├── testCalculator.py ├── testcalc.py ├── testhttp.py ├── testpeople.py ├── ulrparse.py ├── webtest.py └── writeread.py /9781484223840.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/lean-python/15d3fcb3bd505fd937bfad6d6a81d510644f280a/9781484223840.jpg -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/lean-python/15d3fcb3bd505fd937bfad6d6a81d510644f280a/LICENSE.txt -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Apress Source Code 2 | 3 | This repository accompanies [*Lean Python*](http://www.apress.com/9781484223840) by Paul Gerrard (Apress, 2016). 4 | 5 | ![Cover image](9781484223840.jpg) 6 | 7 | Download the files as a zip using the green button, or clone the repository to your machine using Git. 8 | 9 | ## Releases 10 | 11 | Release v1.0 corresponds to the code in the published book, without corrections or updates. 12 | 13 | ## Contributions 14 | 15 | See the file Contributing.md for more information on how you can contribute to this repository. 16 | -------------------------------------------------------------------------------- /contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing to Apress Source Code 2 | 3 | Copyright for Apress source code belongs to the author(s). However, under fair use you are encouraged to fork and contribute minor corrections and updates for the benefit of the author(s) and other readers. 4 | 5 | ## How to Contribute 6 | 7 | 1. Make sure you have a GitHub account. 8 | 2. Fork the repository for the relevant book. 9 | 3. Create a new branch on which to make your change, e.g. 10 | `git checkout -b my_code_contribution` 11 | 4. Commit your change. Include a commit message describing the correction. Please note that if your commit message is not clear, the correction will not be accepted. 12 | 5. Submit a pull request. 13 | 14 | Thank you for your contribution! -------------------------------------------------------------------------------- /programs/calc.py: -------------------------------------------------------------------------------- 1 | def calc(a, op, b): 2 | 3 | if op not in '+-/*': 4 | return None, 'Operator must one of be +-/*' 5 | 6 | try: 7 | if op=='+': 8 | result=a+b 9 | elif op=='-': 10 | result=a-b 11 | elif op=='/': 12 | result=a/b 13 | else: 14 | result=a*b 15 | except Exception,e: 16 | return None,e.__class__.__name__ 17 | 18 | return result,str(result) 19 | 20 | -------------------------------------------------------------------------------- /programs/calculator.py: -------------------------------------------------------------------------------- 1 | 2 | class calculator(object): 3 | 4 | def __init__(self,title): 5 | self.title=title 6 | return 7 | 8 | def runTest(self,a,op,b): 9 | self.result=self.calculate(a,op,b) 10 | return self.result 11 | 12 | def calculate(self,a,op,b): 13 | if len(a)==0 or len(b)==0 or len(op)==0: 14 | return 'Ending' 15 | 16 | def dispose(self): 17 | return 18 | 19 | if __name__=='__main__': 20 | main() -------------------------------------------------------------------------------- /programs/command.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import sys 3 | 4 | nargs=len(sys.argv) 5 | print('%d argument(s)' % (nargs)) 6 | n=0 7 | for a in sys.argv: 8 | print(' arg %d is %s' % (n,a)) 9 | n+=1 10 | -------------------------------------------------------------------------------- /programs/dbcreate.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import os 3 | import sqlite3 4 | 5 | db_filename='mydatabase.db' 6 | # 7 | # if DB exists - delete it 8 | # 9 | exists = os.path.exists(db_filename) 10 | if exists: 11 | os.unlink(db_filename) 12 | # 13 | # connect to DB (create it if it doesn't exist) 14 | # 15 | conn = sqlite3.connect(db_filename) 16 | # 17 | # create a table 18 | # 19 | schema="""create table person ( 20 | id integer primary key autoincrement not null, 21 | name text not null, 22 | dob date, 23 | nationality text, 24 | gender text) 25 | """ 26 | conn.executescript(schema) 27 | # 28 | # create some data 29 | # 30 | people="""insert into person (name, dob,nationality,gender) 31 | values ('Fred Bloggs', '1965-12-25','British','Male'); 32 | insert into person (name, dob,nationality,gender) 33 | values ('Santa Claus', '968-01-01','Lap','Male'); 34 | insert into person (name, dob,nationality,gender) 35 | values ('Tooth Fairy', '1931-03-31','American','Female'); 36 | """ 37 | conn.executescript(people) 38 | # 39 | # execute a query 40 | # 41 | cursor = conn.cursor() 42 | cursor.execute("select id, name, dob,nationality,gender from person") 43 | for row in cursor.fetchall(): 44 | id, name, dob,nationality,gender = row 45 | print("%3d %15s %12s %10s %6s" % (id, name, dob,nationality,gender)) 46 | # 47 | # attempt to insert a person with no name 48 | # 49 | try: 50 | dupe="insert into person (id, dob,nationality,gender) \ 51 | values (1,'1931-03-31','American','Female');" 52 | conn.executescript(dupe) 53 | except Exception,e: 54 | print('Cannot insert record',e.__class__.__name__) -------------------------------------------------------------------------------- /programs/dbupdate.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import sqlite3 3 | import sys 4 | # 5 | # arguments from command line 6 | # use: python dbupdate.py 1 Chinese 7 | # 8 | db_filename = 'mydatabase.db' 9 | inid = sys.argv[1] 10 | innat = sys.argv[2] 11 | # 12 | # execute update using command line arguments 13 | # 14 | conn = sqlite3.connect(db_filename) 15 | cursor = conn.cursor() 16 | query = "update person set nationality = :nat where id = :id" 17 | cursor.execute(query, {'id':inid, 'nat':innat}) 18 | # 19 | # list the persons to see changes 20 | # 21 | cursor.execute("select id, name, dob,nationality,gender from person") 22 | for row in cursor.fetchall(): 23 | id, name, dob,nationality,gender = row 24 | print("%3d %15s %12s %10s %6s" % (id, name, dob,nationality,gender)) 25 | 26 | -------------------------------------------------------------------------------- /programs/division.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | print('Input two numbers. the first will be divided by the second') 3 | 4 | afirst = raw_input('first number:') 5 | first=float(afirst) 6 | asecond = raw_input('second number:') 7 | second = float(asecond) 8 | 9 | quotient = first / second 10 | print('Quotient first/second = ',quotient) 11 | -------------------------------------------------------------------------------- /programs/divisionHandled.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | print('Input two numbers. The first will be divided by the second') 3 | 4 | afirst = raw_input('first number:') 5 | asecond = raw_input('second number:') 6 | 7 | try: 8 | first=float(afirst) 9 | second = float(asecond) 10 | quotient = first / second 11 | print('Quotient first/second = ',quotient) 12 | except Exception, e: 13 | print(e.__class__.__name__,':',e) 14 | 15 | -------------------------------------------------------------------------------- /programs/divisionHandledV2.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | print('Input two numbers. The first will be divided by the second') 3 | 4 | afirst = raw_input('first number:') 5 | try: 6 | first=float(afirst) 7 | asecond = raw_input('second number:') 8 | try: 9 | second = float(asecond) 10 | try: 11 | quotient = first / second 12 | print('Quotient first/second = ',quotient) 13 | except ZeroDivisionError, e: 14 | print(e,': Second number must be non-zero') 15 | except ValueError, e: 16 | print(e,'Second number') 17 | except ValueError, e: 18 | print(e,'First number') -------------------------------------------------------------------------------- /programs/duckduckgo.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | import urllib 4 | import urllib2 5 | import urlparse 6 | import json 7 | # 8 | # we'll use the DuckDuckGo 'Instant Answer' API 9 | # 10 | url='http://api.duckduckgo.com/' 11 | # 12 | # what to search for? 13 | # 14 | search=raw_input('Enter search string:') 15 | if len(search)==0: 16 | exit() 17 | # 18 | # construct the query string by encoding 19 | # the name:value pairs 20 | # 21 | q=dict(q=search,format='json') 22 | qstring=urllib.urlencode(q) 23 | url='?'.join((url,qstring)) 24 | dosave=raw_input('Save downloaded page to disk? [y/n]') 25 | save=dosave in ['y','Y'] 26 | print('Requesting',url,'and save?',save) 27 | # 28 | # execute the query 29 | # 30 | try: 31 | response = urllib2.urlopen(url) 32 | except Exception,e: 33 | print(e.__class__.__name__,e) 34 | exit(0) 35 | # 36 | # we have a response so save it? 37 | # 38 | if save: 39 | fname='save.html' 40 | print('saving to',fname,'...') 41 | fp=open(fname,'w') 42 | fp.write(response.read()) 43 | fp.close() 44 | # 45 | # otherwise display at the terminal 46 | # 47 | else: 48 | jtext=response.read() 49 | jcode=json.loads(jtext) 50 | print(json.dumps(jcode,indent=2,separators=(',', ': '))) -------------------------------------------------------------------------------- /programs/mod1.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | def hello(): 4 | print('hello') 5 | 6 | writtenby='Paul' 7 | print(writtenby) 8 | 9 | class greeting(): 10 | def morning(self): 11 | print('Good Morning!') 12 | def evening(self): 13 | print('Good Evening!') -------------------------------------------------------------------------------- /programs/mod1.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/lean-python/15d3fcb3bd505fd937bfad6d6a81d510644f280a/programs/mod1.pyc -------------------------------------------------------------------------------- /programs/mydatabase.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/lean-python/15d3fcb3bd505fd937bfad6d6a81d510644f280a/programs/mydatabase.db -------------------------------------------------------------------------------- /programs/people.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | from datetime import datetime 3 | 4 | class person(object): 5 | "Person Class" 6 | def __init__(self,name,age,parent=None): 7 | self.name=name 8 | self.age=age 9 | self.created=datetime.today() 10 | self.parent=parent 11 | self.children=[] 12 | print('Created',self.name,'age',self.age) 13 | 14 | def updateName(self,name): 15 | self.name=name 16 | print('Updated name',self.name) 17 | 18 | def updateAge(self,age): 19 | self.age=age 20 | print('Updated age',self.age) 21 | 22 | def addChild(self,name,age): 23 | child=person(name,age,parent=self) 24 | self.children.append(child) 25 | print(self.name,'added child',child.name) 26 | 27 | def listChildren(self): 28 | if len(self.children)>0: 29 | print(self.name,'has children:') 30 | for c in self.children: 31 | print(' ',c.name) 32 | else: 33 | print(self.name,'has no children') 34 | 35 | def getChildren(self): 36 | return self.children -------------------------------------------------------------------------------- /programs/people.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/lean-python/15d3fcb3bd505fd937bfad6d6a81d510644f280a/programs/people.pyc -------------------------------------------------------------------------------- /programs/re.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import httplib # the library to download web pages 3 | import re # The RegEx library 4 | # 5 | # this code opens a connection to the leanpy.com website 6 | # 7 | conn = httplib.HTTPConnection("leanpy.com") 8 | conn.request("GET", "/") 9 | r1 = conn.getresponse() # get the home page text 10 | print(r1.status, r1.reason) # print the status and message 11 | data1 = r1.read() # put response text in data 12 | # 13 | # our regular expression (to find links) 14 | # 15 | regex = ']*href\s*=\s*\"([^\"]*)\"[^>]*>(.*?)' 16 | # 17 | # compile the regex and perform the match (find all) 18 | # 19 | pm = re.compile(regex) 20 | matches = pm.findall(data1) 21 | # 22 | # matches is a list 23 | # m[0] - the url of the link 24 | # m[1] - text associated with the link 25 | # 26 | for m in matches: 27 | ms=''.join(('Link: "',m[0],'" Text: "',m[1],'"')) 28 | print(ms) 29 | 30 | conn.close() 31 | -------------------------------------------------------------------------------- /programs/remail.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import re # The RegEx library 3 | # 4 | # our regular expression (to find emails) 5 | # and text to search 6 | # 7 | regex = '\s[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}[\s\.]' 8 | text="""This is some text with x@y.z embedded emails 9 | that we'll use as@example.com 10 | some lines have no email @ddresses 11 | others@have.two valid email@addresses.com 12 | The re module is awonderful@thing.""" 13 | print('** Search text ***\n'+text) 14 | print('** Regex ***\n'+regex+'\n***') 15 | # 16 | # uppercase our text 17 | utext=text.upper() 18 | # 19 | # perform a search 20 | m = re.search(regex,utext) 21 | if m: 22 | print('Search found','"'+m.group()+'"') 23 | # 24 | # find all matches 25 | m = re.findall(regex,utext) 26 | if m: 27 | for match in m: 28 | print('Match found',match.strip()) 29 | -------------------------------------------------------------------------------- /programs/test1.py: -------------------------------------------------------------------------------- 1 | import mod1 as m1 2 | 3 | m1.hello() 4 | print 'written by', m1.writtenby 5 | 6 | greet = m1.greeting() 7 | greet.morning() 8 | greet.evening() -------------------------------------------------------------------------------- /programs/test2.py: -------------------------------------------------------------------------------- 1 | from mod1 import * 2 | 3 | hello() 4 | hello.writtenby='xxx' 5 | print 'written by', hello.writtenby 6 | print mod1.writtenby 7 | 8 | greet = greeting() 9 | greet.morning() 10 | greet.evening() -------------------------------------------------------------------------------- /programs/testCalculator.py: -------------------------------------------------------------------------------- 1 | 2 | # 3 | # Unit tests for Story 94 Feature: "Calculator" 4 | # 5 | 6 | import unittest 7 | import calculator 8 | 9 | class CalculatorTestCase(unittest.TestCase): 10 | 11 | def setUp(self): 12 | self.calculator = calculator.calculator("The calculator") 13 | 14 | def tearDown(self): 15 | self.calculator.dispose() 16 | self.calculator = None 17 | 18 | 19 | def testPerformCalculation0001(self): 20 | self.calculator.runTest('','','') 21 | self.assertEqual(str(self.calculator.result),"Ending") 22 | 23 | def testPerformCalculation0002(self): 24 | self.calculator.runTest('1','','') 25 | self.assertEqual(str(self.calculator.result),"Ending") 26 | 27 | def testPerformCalculation0003(self): 28 | self.calculator.runTest('1','+','') 29 | self.assertEqual(str(self.calculator.result),"Ending") 30 | 31 | def testPerformCalculation0004(self): 32 | self.calculator.runTest('abc','+','1') 33 | self.assertEqual(str(self.calculator.result),"A is not a number") 34 | 35 | def testPerformCalculation0005(self): 36 | self.calculator.runTest('1','+','pqr') 37 | self.assertEqual(str(self.calculator.result),"B is not a number") 38 | 39 | def testPerformCalculation0006(self): 40 | self.calculator.runTest('1','x','1') 41 | self.assertEqual(str(self.calculator.result),"Invalid operator") 42 | 43 | def testPerformCalculation0007(self): 44 | self.calculator.runTest('-1,000,000,000.000001','+','1') 45 | self.assertEqual(str(self.calculator.result),"A out of range") 46 | 47 | def testPerformCalculation0008(self): 48 | self.calculator.runTest('1000000000.000001','+','1') 49 | self.assertEqual(str(self.calculator.result),"A out of range") 50 | 51 | def testPerformCalculation0009(self): 52 | self.calculator.runTest('1','+','-1000000O00.000001') 53 | self.assertEqual(str(self.calculator.result),"B out of range") 54 | 55 | def testPerformCalculation0010(self): 56 | self.calculator.runTest('1','+','1000000000.000001') 57 | self.assertEqual(str(self.calculator.result),"B out of range") 58 | 59 | def testPerformCalculation0011(self): 60 | self.calculator.runTest('-1000000000.00000','+','-1000000000.00000') 61 | self.assertEqual(str(self.calculator.result),"-2000000000.0") 62 | 63 | def testPerformCalculation0012(self): 64 | self.calculator.runTest('1000000000.00000','+','1000000000.00000') 65 | self.assertEqual(str(self.calculator.result),"2000000000.0") 66 | 67 | def testPerformCalculation0013(self): 68 | self.calculator.runTest('1','-','1') 69 | self.assertEqual(str(self.calculator.result),"0.0") 70 | 71 | def testPerformCalculation0014(self): 72 | self.calculator.runTest('1','*','1') 73 | self.assertEqual(str(self.calculator.result),"1.0") 74 | 75 | def testPerformCalculation0015(self): 76 | self.calculator.runTest('1','/','1') 77 | self.assertEqual(str(self.calculator.result),"1.0") 78 | 79 | calculatorTestSuite = unittest.TestSuite() 80 | 81 | calculatorTestSuite.addTest(CalculatorTestCase("testPerformCalculation0001")) 82 | calculatorTestSuite.addTest(CalculatorTestCase("testPerformCalculation0002")) 83 | calculatorTestSuite.addTest(CalculatorTestCase("testPerformCalculation0003")) 84 | """ 85 | calculatorTestSuite.addTest(CalculatorTestCase("testPerformCalculation0004")) 86 | calculatorTestSuite.addTest(CalculatorTestCase("testPerformCalculation0005")) 87 | calculatorTestSuite.addTest(CalculatorTestCase("testPerformCalculation0006")) 88 | calculatorTestSuite.addTest(CalculatorTestCase("testPerformCalculation0007")) 89 | calculatorTestSuite.addTest(CalculatorTestCase("testPerformCalculation0008")) 90 | calculatorTestSuite.addTest(CalculatorTestCase("testPerformCalculation0009")) 91 | calculatorTestSuite.addTest(CalculatorTestCase("testPerformCalculation0010")) 92 | calculatorTestSuite.addTest(CalculatorTestCase("testPerformCalculation0011")) 93 | calculatorTestSuite.addTest(CalculatorTestCase("testPerformCalculation0012")) 94 | calculatorTestSuite.addTest(CalculatorTestCase("testPerformCalculation0013")) 95 | calculatorTestSuite.addTest(CalculatorTestCase("testPerformCalculation0014")) 96 | calculatorTestSuite.addTest(CalculatorTestCase("testPerformCalculation0015")) """ 97 | 98 | runner = unittest.TextTestRunner() 99 | runner.run(calculatorTestSuite) 100 | -------------------------------------------------------------------------------- /programs/testcalc.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import calc 3 | # 4 | # define the test class 5 | # 6 | class testCalc(unittest.TestCase): 7 | 8 | def setUp(self): 9 | print '^', 10 | return 11 | def tearDown(self): 12 | print 'v', 13 | return 14 | 15 | def testSimpleAdd(self): 16 | result,msg = calc.calc(1,'+',1) 17 | self.assertEqual(result,2.0) 18 | 19 | def testLargeProduct(self): 20 | result,msg = calc.calc(123456789.0,'*',987654321.0) 21 | self.assertEqual(result,1.2193263111263526e+17) 22 | 23 | def testDivByZero(self): 24 | result,msg = calc.calc(6,'/',0.0) 25 | self.assertEqual(msg,'ZeroDivisionError') 26 | # 27 | # create the test suite 28 | # 29 | TestSuite = unittest.TestSuite() 30 | # 31 | # add tests to the suite 32 | # 33 | TestSuite.addTest(testCalc("testSimpleAdd")) 34 | TestSuite.addTest(testCalc("testLargeProduct")) 35 | TestSuite.addTest(testCalc("testDivByZero")) 36 | # 37 | # create the test runner 38 | # 39 | runner = unittest.TextTestRunner() 40 | # 41 | # execute the tests 42 | # 43 | runner.run(TestSuite) 44 | -------------------------------------------------------------------------------- /programs/testhttp.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import httplib # the library to download web pages 3 | # 4 | # this code opens a connection to the leanpy.com website 5 | # 6 | url=raw_input('Enter website url:') 7 | conn = httplib.HTTPConnection(url) 8 | conn.request("GET", "/") 9 | r1 = conn.getresponse() # get the home page text 10 | print(r1.status, r1.reason) # print the status and message 11 | text = r1.read() # put response text in data 12 | 13 | print(text) 14 | -------------------------------------------------------------------------------- /programs/testpeople.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | from people import person 3 | 4 | # 5 | # create a new instance of class person 6 | # for joe bloggs, age 47 7 | # 8 | joe=person('Joe Bloggs',47) 9 | # 10 | # use the instance variable to verify 11 | # Joe's name/age 12 | # 13 | print("Joe's age is",joe.age) 14 | print("Joe's full name is ",joe.name) 15 | # 16 | # add children Dick and Dora 17 | # 18 | joe.addChild('Dick',7) 19 | joe.addChild('Dora',9) 20 | # 21 | # use thelistChildren method to list them 22 | # 23 | joe.listChildren() 24 | # 25 | # get the list variable containing Joe's children 26 | # 27 | joekids=joe.getChildren() 28 | # 29 | # print Joe's details. 30 | # NB the vars() function lists the values 31 | # of the instance attributes 32 | # 33 | print("** Joe's attributes **") 34 | print(vars(joe)) 35 | # 36 | # print the details of his children 37 | # from the list we obtained earlier 38 | # 39 | print("** Joe's Children **") 40 | for j in joekids: 41 | print(j.name,'attributes') 42 | print(vars(j)) 43 | -------------------------------------------------------------------------------- /programs/ulrparse.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | -------------------------------------------------------------------------------- /programs/webtest.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | import urllib 4 | import urllib2 5 | import urlparse 6 | 7 | path='' 8 | url=raw_input('Web url to fetch:') 9 | urlparts=urlparse.urlparse(url) 10 | if urlparts[0]=='': 11 | url=''.join(('http://',url)) 12 | print(str(urlparts)) 13 | 14 | qstring=raw_input('Enter query string:') 15 | 16 | save=raw_input('Save downloaded page to disk [y/n]?') 17 | if len(qstring)>0: 18 | url='?'.join((url,qstring)) 19 | 20 | print('Requesting',url) 21 | 22 | try: 23 | response = urllib2.urlopen(url) 24 | if save.lower()=='y': 25 | geturl=response.geturl() 26 | urlparts=urlparse.urlparse(geturl) 27 | for p in urlparts: 28 | print(p) 29 | path=urlparts[2] 30 | if len(path)==0: 31 | fname='save.html' 32 | else: 33 | fname='_'.join(path.split('/')) 34 | fname='_'.join(path.split('\\')) 35 | fname='.'.join((fname,'html')) 36 | print('saving to',fname,'...') 37 | fp=open(fname,'w') 38 | fp.write(response.read()) 39 | fp.close() 40 | else: 41 | print(response.read()) 42 | except Exception,e: 43 | print(e.__class__.__name__,e) 44 | 45 | 46 | -------------------------------------------------------------------------------- /programs/writeread.py: -------------------------------------------------------------------------------- 1 | fp=open('text.txt','r') 2 | for l in fp: 3 | print l, 4 | fp.close() 5 | 6 | fp = open('text.txt','w') 7 | while True: 8 | text = raw_input('Enter text (end with blank):') 9 | if len(text)==0: 10 | break 11 | else: 12 | fp.write(text+'\n') 13 | fp.close() 14 | 15 | 16 | nfile='doesnotexist.txt' 17 | fp=open(nfile,'r') 18 | try: 19 | fp=open(nfile,'r') 20 | except: 21 | print'Cannot open',nfile,'for reading. Does not exist' 22 | 23 | 24 | 25 | 26 | fp=open('tempfile.txt','w') 27 | # for i= 28 | fp.close() --------------------------------------------------------------------------------