3-1
Python是动态语言,对象的类型和内存都是在运行时确定的。
3-2
Python 中每个函数都会有返回值,如果没有指定,则返回None
如果有return 语句,则返回 return 语句的值
3-3
单下划线 类似于protect
双下划线 类似于private
使用双下划线后,该变量只可以在类里面使用
3-4
可以写多个语句,用 分号 ; 隔开
3-5
一个语句可以分成多行写 ,使用 \ 连接在上一行的末尾
3-6
(a) 多元赋值 x = 1,y = 2,z = 3
(b) 多元赋值,可以看做是交换(同时执行), z = y = 2, x = z = 3,y = x =1
3-7
不合法的标识符
40XL $aving$ 0x40L big-daddy
2hot2touch thisIsn'tAvar counter-1
关键字
print self __name__ bool type True if
3-8
详情代码看Github
- page52 makeTextFile.py 有错误,在10行应该添加
- if 跟 else 还需要缩进,不然会报错
- 在win环境下,输入的文件名应该包含路径,而且路径的分隔符是 / (正斜杠)
3-9
os.linesep不同操作系统下的输出
- win '\r\n'
- Linux '\n'
- Mac '\r'
3-10
try ... catch 与 if 的使用:
当条件多为真时,使用if
当条件多为假时,使用try ... catch
makeFile.py
#!/usr/bin/env python
# coding = utf-8
'makeTextFile.py -- create text file'
import os
ls = os.linesep
# get filename
while True:
fname = raw_input("Please input file name:\n")
try:
with open(fname,'r'): # success ,file exists ; failed, file not exists
print "File exists"
except IOError: #open failed
break
#get file content (text) linesall = []
print "\nEnter lines ('.' by itself to quite) ."
#loop until user terminates input
while True:
entry = raw_input('>>>')
if entry == '.':
break
else:
all.append(entry)
#write lines to file with proper line-ending
fobj = open(fname, 'w')
fobj.writelines(['%s%s' %(x, ls) for x in all])
fobj.close()
print 'Done!'
readFile.py
#!/usr/bin/env python
import os
'readTextFile.py -- read and display text file'
while True:
# get filename
fname = raw_input("Enter filename: ")
print
# attempt to open file for reading
if not os.path.exists(fname):
print " *** file open error!\n"
else:
fobj = open(fname,'r')
# display contents to the screen
for eachLine in fobj:
print eachLine,
fobj.close()
break
3-11
strip()函数,str.strip(rm) 是删除s字符串中开头、结尾处,位于 rm删除序列的字符
字符序列 : 该字符串的无序列表,可以由rm 组成就行。
- 当rm为空时,默认删除空白符 包括 ('\n','\r','\t',' ')
- 这里的rm删除序列是只要边(开头或结尾)上的字符在删除序列内,就删除掉。
>>> a = '123abc'
>>> a.strip('12')
'3abc'
>>> a.strip('21')
'3abc'
>>> a.strip('1a')
'23abc'
>>> a.strip('1c')
'23ab'
>>> a.strip('1b')
'23abc'
>>> a.lstrip('3a')
'123abc'
>>> a.lstrip('12')
'3abc'
>>> a.lstrip('21')
'3abc'
>>> a.lstrip('bc')
'123abc'
>>> a.rstrip('bc')
'123a'
>>> a.rstrip('bac')
'123'
>>> a.rstrip('bca')
'123'
>>> a.strip('3a')
'123abc'
原题答案,只需要把eachLine 后的 逗号改成 .strip()
3-12
思路:把两个文件的功能放在函数里,在main函数里通过while循环判断用户输入的功能序列,在执行相应的功能
#!/usr/bin/env python
__author__ = 'Yuriy'
import os
ls = os.linesep
# get filename
def writeFile():
while True:
fname = raw_input("Please input file name:\n")
if os.path.exists(fname):
print "ERROR: '%s' already exists" %fname
else:
break
#get file content (text) lines
all = []
print "\nEnter lines ('.' by itself to quite) ."
#loop until user terminates input
while True:
entry = raw_input('>>>')
if entry == '.':
break
else:
all.append(entry)
#write lines to file with proper line-ending
fobj = open(fname, 'w')
fobj.writelines(['%s%s' %(x, ls) for x in all])
fobj.close()
print 'Done!'
def readFile():
fname = raw_input("Enter filename: ")
print
# attempt to open file for reading
try:
fobj = open(fname,'r')
except IOError, e:
print " *** file open error:",e
else:
# display contents to the screen
for eachLine in fobj:
print eachLine.strip()
fobj.close()
if __name__ == '__main__':
while True:
print '''Input the function number:
1.MakeFile
2.ReadFile
3.Exit
'''
ch = int(raw_input(' Function :'))
if ch == 1:
writeFile()
elif ch == 2:
readFile()
else:
break
Input the function number:
1.MakeFile
2.ReadFile
3.Exit
Function :1
Please input file name:
e:/eee.txt
Enter lines ('.' by itself to quite) .
>>>my name
>>>is
>>>who
>>>.
Done!
Input the function number:
1.MakeFile
2.ReadFile
3.Exit
Function :2
Enter filename: e:/eee.txt
my name
is
who
Input the function number:
1.MakeFile
2.ReadFile
3.Exit
Function :3
Process finished with exit code 0
3-13
只需要在3-12的基础上再加上一个功能,调用win系统的命令:
os.system('notepad %s' %ch) 就可以使用文本编辑器编辑该txt文件
#!/usr/bin/env python
__author__ = 'Yuriy'
import os
ls = os.linesep
# get filename
def writeFile():
while True:
fname = raw_input("Please input file name:\n")
if os.path.exists(fname):
print "ERROR: '%s' already exists" %fname
else:
break #get file content (text) lines
all = []
print "\nEnter lines ('.' by itself to quite) ."
#loop until user terminates input
while True:
entry = raw_input('>>>')
if entry == '.':
break
else:
all.append(entry)
#write lines to file with proper line-ending
fobj = open(fname, 'w')
fobj.writelines(['%s%s' %(x, ls) for x in all])
fobj.close()
print 'Done!'
def readFile():
fname = raw_input("Enter filename: ")
print
# attempt to open file for reading
try:
fobj = open(fname,'r')
except IOError, e:
print " *** file open error:",e
else:
# display contents to the screen
for eachLine in fobj:
print eachLine.strip()
fobj.close()
def changeFile():
while True:
ch = raw_input("input filename:")
if not os.path.exists(ch):
print "%s File not exists \n" % ch
else:
try:
# call system command to change file content
os.system('notepad %s' %ch
print
print 'You have change %s' % ch
break
except IOError,e:
print 'error command'
if __name__ == '__main__':
while True:
print '''Input the function number:
1.MakeFile
2.ReadFile
3.changeFile
'''
ch = int(raw_input(' Function :'))
if ch == 1:
writeFile()
elif ch == 2:
readFile()
elif ch == 3:
changeFile()
else:
break
Input the function number:
1.MakeFile
2.ReadFile
3.changeFile
Function :3
input filename:e:/eee.txt
You have change e:/eee.txt
网友评论