python学习笔记5

Chat 9 ImportAndException

python可以写入py文件,还可以直接运行文件

%%writefile ex1.py
PI = 3.1416

def sum(lst):
    tot = lst[0]
    for value in lst[1:]:
        tot = tot + value
    return tot
    
w = [0, 1, 2, 3]
print sum(w), PI
%run ex1.py

当然我还可以直接import这个文件

import ex1
print ex1.PI
reload(ex1)
# 重新载入ex1,这样可以重新

import os
os.remove('ex1.py')
# 删除这个文件

有时候我们想将一个 .py 文件既当作脚本,又能当作模块用,这个时候可以使用 __name__ 这个属性。

只有当文件被当作脚本执行的时候, __name__的值才会是 '__main__',所以我们可以:

if __name__ == '__main__':

假设我们有这样的一个文件夹:

foo/

  • __init__.py
  • bar.py (defines func)
  • baz.py (defines zap)

导入包要求:

  • 文件夹 fooPython的搜索路径中
  • __init__.py 表示 foo 是一个包,它可以是个空文件。

似乎python3里面是不需要写东西的

python2需要写import bar, baz


介绍下异常

下面这个函数如果是负数,那么会有bug

import math

while True:
    text = raw_input('> ')
    if text[0] == 'q':
        break
    x = float(text)
    y = math.log10(x)
    print "log10({0}) = {1}".format(x, y)

我们可以用try

import math

while True:
    try:
        text = raw_input('> ')
        if text[0] == 'q':
            break
        x = float(text)
        y = math.log10(x)
        print "log10({0}) = {1}".format(x, y)
    except ValueError:
        print "the value must be greater than 0"
import math

while True:
    try:
        text = raw_input('> ')
        if text[0] == 'q':
            break
        x = float(text)
        y = 1 / math.log10(x)
        print "1 / log10({0}) = {1}".format(x, y)
    except Exception:
        print "invalid value"
import math

while True:
    try:
        text = raw_input('> ')
        if text[0] == 'q':
            break
        x = float(text)
        y = 1 / math.log10(x)
        print "1 / log10({0}) = {1}".format(x, y)
    except (ValueError, ZeroDivisionError):
        print "invalid value"
import math

while True:
    try:
        text = raw_input('> ')
        if text[0] == 'q':
            break
        x = float(text)
        y = 1 / math.log10(x)
        print "1 / log10({0}) = {1}".format(x, y)
    except ValueError:
        print "the value must be greater than 0"
    except ZeroDivisionError:
        print "the value must not be 1"
# 这样就可以像if elif一样
import math

while True:
    try:
        text = raw_input('> ')
        if text[0] == 'q':
            break
        x = float(text)
        y = 1 / math.log10(x)
        print "1 / log10({0}) = {1}".format(x, y)
    except ValueError as exc:
        if exc.message == "math domain error":
            print "the value must be greater than 0"
        else:
            print "could not convert '%s' to float" % text
    except ZeroDivisionError:
        print "the value must not be 1"
    except Exception as exc:
        print "unexpected error:", exc.message

当我们使用 except Exception 时,会捕获所有的 Exception 和它派生出来的子类,但不是所有的异常都是从 Exception 类派生出来的,可能会出现一些不能捕获的情况,因此,更加一般的做法是使用这样的形式:

try:
    pass
except:
    pass

这样不指定异常的类型会捕获所有的异常,但是这样的形式并不推荐。

我们还可以使用finally,就是不管怎么样,都会执行

try:
    print 1 / 0
except ZeroDivisionError:
    print 'divide by 0.'
finally:
    print 'finally was called.'

Chat10 Warning and IO

有些情况下,我想让程序继续运行,然后我又需要用户知道以下事情

import warnings

def month_warning(m):
    if not 1<= m <= 12:
        msg = "month (%d) is not between 1 and 12" % m
        warnings.warn(msg, RuntimeWarning)

month_warning(13)

warnings.filterwarnings(action = 'ignore', category = RuntimeWarning)

month_warning(13)

下面介绍下IO操作

写入测试文件:

%%writefile test.txt
this is a test file.
hello world!
python is good!
today is a good day.

读文件

f = open('test.txt')
f = file('test.txt')

text = f.read()
print text

f = open('test.txt')
lines = f.readlines()
print lines
# readlines 方法返回一个列表,每个元素代表文件中每一行的内容:
f.close()

写文件

f = open('myfile.txt', 'w')
f.write('hello world!')
f.close()

print open('myfile.txt').read()

f = open('myfile.txt', 'w+')
f.write('hello world!')
f.seek(6)
print f.read()
f.close()
# seek就是移动到第4个字符

猜你喜欢

转载自www.cnblogs.com/Basasuya/p/9000490.html