文件读取
读取模式('r')、写入模式写入模式('w')、附加模式附加模式('a')或让你能够读取和写入文件的模式('r+'
如果要写入的文件不存在,函数open()将自动创建它。然而,以写入('w')模式打开文件时千万要小心,因为如果指定的文件已经存在,Python将在返回文件对象前清空该文件
python只能将字符串写入文本文件。要将数值数据存储到文本文件中,必须先使用函数str()将其转换为字符串格式。
1 # f=open('test.txt','r+')
2 # f.write('Avaya')#新内容会添加在文件的开头,并且会覆盖开头原有的内容
3 # f.close()
4
5
6
7 # f=open('test.txt','w')
8 # f.write('test') #w模式下使用write,会把文件内容清空然后在开头写入内容
9 # f.close()
10
11 # f=open('test.txt','w+')
12 # f.write('test1')#效果与上面一样
13 # f.close()
14
15 # f=open('test.txt','a')
16 # f.write('Hillstone') #会在文件末尾追加
17 # f.close()
18
19 # f=open('test.txt')
20 # print(f.closed)#closed方法会返回一个布尔值,如果是打开状态就是fales
21 # f.close()
22 # print(f.closed)
23
24
25 # with open('test.txt')as f: #with语句打开的文件将自动关闭
26 # print(f.read())
27 # print(f.closed)
异常
ZeroDivisionError异常
1 try:
2 print(5/0)
3 except ZeroDivisionError:
4 print("You can't divide by zero")
5
6 You can't divide by zero
处理FileNotFoundError异常
1 filename='alice.txt'
2 with open(filename) as f_obj:
3 contents = f_obj.read()
4 Python无法读取不存在的文件,因此它引发一个异常:
5 Traceback (most recent call last):
6 File "E:/untitled1/alice.py", line 2, in <module>
7 with open(filename) as f_obj:
8 FileNotFoundError: [Errno 2] No such file or directory: 'alice.txt'
9
10 filename='alice.txt'
11 try:
12 with open(filename) as f_obj:
13 contents = f_obj.read()
14 except FileNotFoundError:
15 msg="Sorry,the file "+filename+" does not exist."
16 print(msg)
失败时一声不吭
1 filename='alice.txt'
2 try:
3 with open(filename) as f_obj:
4 contents = f_obj.read()
5 except FileNotFoundError:
6 pass#不提示错误消息
7 else:
8 # 计算文件大致包含多少个单词
9 words= contents.split()
10 num_words=len(words)
11 print("The file "+filename+" has about "+str(num_words)+" words.")
来源:oschina
链接:https://my.oschina.net/u/4275644/blog/4342890