8. 从文件中读取
将整个文件内容读取到变量s
中
f = open('test.txt')
s = f.read()
f.close()
也可使用readline
方法一次读取文本文件的一行
若文件不存在或由于其他原因文件不可读,上面的操作便会抛出异常,我们可通过将代码放入try/except
结构中的方式处理这个异常:
try:
f = open('test.txt')
s = f.read()
f.close()
except IOError:
print('Cannot open this file')
9. Pickling
可将整个数据结构中的内容存入文件以便程序下次运行时能够读取。
将一个复杂的列表结构存储到文件中:
>>> import pickle
>>> mylist = [23, 'abc', [44, 12]]
>>> f = open('mylist.pickle', 'wb')
>>> pickle.dump(mylist, f)
>>> f.close()
将文件中内容转回到新列表中:
>>> f = open('mylist.pickle', 'rb')
>>> other_array = pickle.load(f)
>>> f.close()
>>> other_array
[23, 'abc', [44, 12]]
Pickling 可以作用于几乎任何数据结构。
10. 处理异常
使用Python 的try
/except
结构:
try:
f = open('test.txt')
s = f.read()
f.close()
except IOError:
print('Cannot open this file')
可使用except
节捕获不同类型的异常并使用不同的方式处理它们。若不特别指定异常类,将会捕获所有的异常。
也可使用else
和finally
子句:
list = [1, 2, 3]
try:
list[8]
except:
print('out of range')
else:
print('in range')
finally:
print('always do this')
若无异常,else
子句将执行,同时不论有无异常,finally
子句都将执行。
若既要打印指定异常语句,又要获取其自身异常语句,可使用as
关键字:
>>> list = [1, 2, 3]
>>> try:
... list[5]
...except Exception as e:
... print('out of range')
... print(e)
...
out of range
list index out of range
11. 使用模块
使用import
命令:
在访问模块中任何函数或是变量时必须加前缀XX.
访问所有内容from random import *
明确指定程序中使用模块中的哪些组件from random import randint
引用模块时使用as 为模块提供更方便或更有意义的名称import random as R
12. 随机数
使用random
库
>>> import random
>>> random.randint(1, 6)
6
>>> random.randint(1, 6)
1
>>> random.randint(1, 6)
4
随机数的通常做法是从一个列表中随机选取元素。可通过生成一个位置索引并使用它的方式达成这一目的:
>>> import random
>>> random.choice(['a', 1, 'b', 2, 'c'])
'a'
>>> random.choice(['a', 1, 'b', 2, 'c'])
2
>>> random.choice(['a', 1, 'b', 2, 'c'])
'c'
13. 从Python 中发送web 请求
将网站的主页内容读取到字符串变量中:
>>> import urllib.request
>>> contents = urllib.request.urlopen("http://www.baidu.com").read()
>>> print(contents)
14. Python 中的命令行参数
sys.argv[]
实际上就是列表,其保存的就是用户在命令行当中所输入的参数
import sys
name = sys.argv[0]
print(name)
a = sys.argv[1]
print(a)
b = sys.argv[2]
print(b)
c = sys.argv[3]
print(c)
将该代码保存为test.py
,并在命令行中运行python test.py a b c
输出结果为:
test.py
a
b
c
能够在命令行中指定参数对于在启动阶段或者指定时间自动运行Python 程序是很有用的