forked from adaptives/python-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython_files.py
More file actions
executable file
·50 lines (46 loc) · 1.34 KB
/
python_files.py
File metadata and controls
executable file
·50 lines (46 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/usr/bin/python
import os
def read_file(name):
print 'printing contents of file ' + name
f = None
#We use try...finally to ensure that the file is closed even if there
#is a problem while processing it
try:
f = file(name, 'r')
line = f.readline()
while(len(line) != 0):
print line, #notice the , to prevent printing a newline character
line = f.readline()
finally:
if f != None:
f.close()
def create_module(name):
print 'creating module ' + name
f = None
#We use try...finally to ensure that the file is closed even if there
#is a problem while processing it
try:
f = file(name, 'w')
#Notice that a newline is not inserted automatically
#There is no println in Python
f.write('#!/usr/bin/python\n')
f.write('# Filename : ' + name + '\n')
f.write("'''Class comment to be completed.'''\n")
f.write('\n')
f.write('def __init__():\n')
f.write('\n')
f.write('def __str__():\n')
f.write('\n')
finally:
if f != None:
f.close()
name = '/home/pshah/tmp/tmp.py'
#Use exceptions to make the program fail gracefully and provide a meaningful
#message to the user
try:
create_module('/home/pshah/tmp1/tmp.py')
read_file(name)
#Remove the file so we do not pollute the disk
os.remove(name)
except Exception, e:
print 'An error ocurred in this program ', e