标签:python
今天学习了python的输入输出、异常处理和python标准库
1.文件
通过创建一个file类的对象去处理文件,方法有read、readline、write、close等
[root@reed 0505]# cat using_file.py
#!/usr/bin/python
#filename:using_file.py
poem=‘‘‘Programing is fun
when the work is done
use Python!
‘‘‘
f=file(‘poem.txt‘,‘w‘)#open for writng
f.write(poem)#write text to file
f.close()#close the file
f=file(‘poem.txt‘)
#default is read
while True:
        line=f.readline()
        if len(line)==0:
                break
        print line,
f.close()
[root@reed 0505]# ./using_file.py
Programing is fun
when the work is done
use Python!2.储存器
Python提供一个标准的模块,称为pickle。使用它你可以在一个文件中储存任何Python对象,之后你又可以把它完整无缺地取出来。这被称为 持久地 储存对象。
[root@reed 0505]# cat picking.py #!/usr/bin/python #filename:picking.py import cPickle as p shoplistfile=‘shoplist.data‘ #the name of the file where we will store the object shoplist=[‘apple‘,‘mango‘,‘carrot‘] #write to the file f=file(shoplistfile,‘w‘) p.dump(shoplist,f)#dump the object to a file f.close() del shoplist #remove the shoplist #read back from the storage f=file(shoplistfile) storedlist=p.load(f) print storedlist [root@reed 0505]# ./picking.py [‘apple‘, ‘mango‘, ‘carrot‘]
3.try...except
[root@reed 0505]# cat try_except.py
#!/usr/bin/python
#filename:try_except.py
import sys
try:
        s=raw_input(‘enter:‘)
except EOFError:
        print ‘\nwhy did u do an EOF on me?‘
        sys.exit()#exit the program
except:
        print ‘\nsome error/exception occurred‘
print ‘done‘
[root@reed 0505]# ./try_except.py
enter:^C
some error/exception occurred
done
[root@reed 0505]# ./try_except.py
enter:
why did u do an EOF on me?
[root@reed 0505]#4.try...finally
假如你在读一个文件的时候,希望在无论异常发生与否的情况下都关闭文件,该怎么做呢?这可以使用finally块来完成。注意,在一个try块下,你可以同时使用except从句和finally块。如果你要同时使用它们的话,需要把一个嵌入另外一个。
[root@reed 0505]# cat finally.py
#!/usr/bin/python
#filename:finally.py
import time
try:
        f=file(‘poem.txt‘)
        while True:
                line=f.readline()
                if len(line)==0:
                        break
                time.sleep(2)
                print line,
finally:
        f.close()
        print ‘cleaning up...close the file‘
[root@reed 0505]# ./finally.py
Programing is fun
when the work is done
^Ccleaning up...close the file
Traceback (most recent call last):
  File "./finally.py", line 11, in <module>
    time.sleep(2)
KeyboardInterrupt
[root@reed 0505]#5.sys模块
[root@reed 0505]# cat cat.py
#!/usr/bin/python
#filename:cat.py
import sys
def readfile(filename):
        f=file(filename)
        while True:
                line=f.readline()
                if len(line)==0:
                        break
                print line,
        f.close()
if len(sys.argv)<2:
        print ‘no action specified‘
        sys.exit()
if sys.argv[1].startswith(‘--‘):
        option=sys.argv[1][2:]
        if option==‘version‘:
                print ‘version 1.2‘
        elif option==‘help‘:
                print ‘‘‘--version:print version\n--help:help me‘‘‘
        else:
                print ‘unknown option‘
        sys.exit()
else:
        for filename in sys.argv[1:]:
                readfile(filename)
[root@reed 0505]# ./cat.py
no action specified
[root@reed 0505]# ./cat.py --help
--version:print version
--help:help me
[root@reed 0505]# ./cat.py --a
unknown option
[root@reed 0505]#知识补充:
sys.argv[]是用来获取命令行参数的,sys.argv[0]表示代码本身文件路径;比如在CMD命令行输入 “python  test.py -help”,那么sys.argv[0]就代表“test.py”。sys.startswith() 是用来判断一个对象是以什么开头的,比如在python命令行输入“‘abc‘.startswith(‘ab‘)”就会返回Truesys.argv[1][2:]表示从第二个参数,从第三个字符开始截取到最后结尾
6.os模块
下面列出了一些在os模块中比较有用的部分。它们中的大多数都简单明了。
● os.name字符串指示你正在使用的平台。比如对于Windows,它是‘nt‘,而对于Linux/Unix用户,它是‘posix‘。
● os.getcwd()函数得到当前工作目录,即当前Python脚本工作的目录路径。
● os.getenv()和os.putenv()函数分别用来读取和设置环境变量。
● os.listdir()返回指定目录下的所有文件和目录名。
● os.remove()函数用来删除一个文件。
● os.system()函数用来运行shell命令。
● os.linesep字符串给出当前平台使用的行终止符。例如,Windows使用‘\r\n‘,Linux使用‘\n‘而Mac使用‘\r‘。
● os.path.split()函数返回一个路径的目录名和文件名。>>> os.path.split(‘/home/swaroop/byte/code/poem.txt‘)(‘/home/swaroop/byte/code‘, ‘poem.txt‘)
● os.path.isfile()和os.path.isdir()函数分别检验给出的路径是一个文件还是目录。类似地,os.path.exists()函数用来检验给出的路径是否真地存在。
本文出自 “reed卢伟开技术学习博客” 博客,谢绝转载!
[简明python教程]学习笔记2014-05-05,布布扣,bubuko.com
标签:python
原文地址:http://luweikai.blog.51cto.com/1705672/1406929