【三】文件与异常

  1. python如何从文件读取数据的过程

  • python的基本输入机制是基于行的
  • open()

 【三】文件与异常

  • 在对数据进行处理后需要关闭资源 close()

  【三】文件与异常

什么是异常?

  异常即是一个事件,该事件会在程序执行过程中发生,影响了程序的正常执行。当Python脚本发生异常时我们需要捕获处理它,否则程序会终止执行。

  捕捉异常可以使用try/except语句。

  try/except语句用来检测try语句块中的错误,从而让except语句捕获异常信息并处理。

  • 当出现异常控制流时需要用到try/excep机制

    【三】文件与异常

open()

  1. 打开文件。
  2. the_file=open("test.txt")

readline()

  1. 读取整行。
  2. print(the_file.readline())

seek()

  1. 移动文件读取指针到指定位置
  2. the_file.seek(0)#回到初始位置

close()

  1. 关闭文件。关闭后文件不能再进行读写操作。
  2. the_file.close()

split()

  1. 通过指定分隔符对字符串进行切片
  2. (role,line_spoken)=i.split(':',1)

find()

  1. 查找字符串中是否包含子字符串,如果包含返回开始的索引值,否则返回-1
  2. a.find("a")

not

  1. 取反
  2.  if not i.find(":")==-1
  3. 等同于if i.find(":")!=-1(如果找到的“:”可以找到)

try/except

  1.  异常处理
  2. try:
    <语句>        #运行别的代码
    except <名字>:
    <语句>        #如果在try部份引发了'name'异常
    except <名字>,<数据>:
    <语句>        #如果引发了'name'异常,获得附加的数据
    else:
    <语句>        #如果没有异常发生

pass

  1. 空语句,一般用做占位语句。
  2. pass()

例子:将文件内的内容读取出来

In [6]: cat test.txt #查看test.txt内容
me:hello,my name is huahua
you:nice
me:year:hah 
In [7]: the_file=open('test.txt')#打开文件
In [8]: print(the_file.readline())#读取文件,每次只读取一行
me:hello,my name is huahua
In [9]: print(the_file.readline())#读取第二句
you:nice
In [10]: the_file.seek(0)#返回初始值
Out[10]: 0
In [11]: print(the_file.readline())
me:hello,my name is huahua

In [13]: import os #导入os模块

In [14]: if os.path.exists('test.txt'): #判断该文件是否存在
    ...:     the_file=open('test.txt')
    ...:     for ii in the_file:
    ...:         try:    #异常处理
    ...:             (role,line_spoken)=ii.split(':',1) #以:分割该字符串
    ...:             print(role,end='')
    ...:             print("said:")
    ...:             print(line_spoken,end='')
    ...:         except:
    ...:             pass
    ...:     data.close()    #关闭连接
    ...: else:
    ...:     print("the_file is missing")
    ...:     
mesaid:
hello,my name is huahua
yousaid:
nice
mesaid:
year:hah