1 1.open使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。
2 file_object = open('thefile.txt')
3 try:
4 all_the_text = file_object.read( )
5 finally:
6 file_object.close( )
7 注:不能把open语句放在try块里,因为当打开文件出现异常时,文件对象file_object无法执行close()方法。
8 2.读文件读文本文件input = open('data', 'r')
9 #第二个参数默认为r
10 input = open('data')
11
12 读二进制文件input = open('data', 'rb')
13 读取所有内容file_object = open('thefile.txt')
14 try:
15 all_the_text = file_object.read( )
16 finally:
17 file_object.close( )
18 读固定字节file_object = open('abinfile', 'rb')
19 try:
20 while True:
21 chunk = file_object.read(100)
22 if not chunk:
23 break
24 do_something_with(chunk)
25 finally:
26 file_object.close( )
27 读每行list_of_all_the_lines = file_object.readlines( )
28 如果文件是文本文件,还可以直接遍历文件对象获取每行:
29 for line in file_object:
30 process line
31 3.写文件写文本文件output = open('data.txt', 'w')
32 写二进制文件output = open('data.txt', 'wb')
33 追加写文件output = open('data.txt', 'a')
34
35 output .write("\n都有是好人")
36
37 output .close( )
38
39 写数据file_object = open('thefile.txt', 'w')
40 file_object.write(all_the_text)
41 file_object.close( )