断断续续看了几天python了,第一次看是在台风的时候,公司说可以在家办公,当时在家也没干活,之前一直想看看Python的东西,那天终于安静的看了一天。今天又把当时看的东西温习了一遍,照着例子写了几行代码,果然Python的话写起来比java舒服一些。
读取文件,然后终端输入,然后读取文件,打印在屏幕
iamzhongyong.py
#!usr/bin/env python
"this is example for make file"
import os
fname = 'C:\\Users\\zhongyong\\Desktop\\python\\file1.txt'
#write file
def fun_write_file():
ls = os.linesep
#get filename
while True:
if os.path.exists(fname):
print "ERROR '%s' already exist" % fname
else:
break
#get file content lines
all = []
print "\nEnter lines ('.' by itselt to quit).\n"
#loop until user terminates input
while True:
entry = raw_input('>')
if entry =='.':
break
else:
all.append(entry)
#write line to file
print fname
fobj = open(fname,'w')
fobj.writelines(['%s%s' %(x,ls) for x in all])
fobj.close()
print 'DONE!'
#read file
def fun_read_file():
try:
f = open(fname,'r')
except IOErro,e:
print 'file open error:',e
else:
for eachLine in f:
print eachLine,
f.close()
if __name__ =='__main__':
fun_write_file()
fun_read_file()
学习过程中看的是《Python 核心编程 第二版》,觉得这本书写的很详细,很基础,比较适合我这种Python菜鸟,期间也找过很多其他材料,觉得还是这本好。有需要学习的,推荐一下呵呵,电子版很多。