Handling files and errors in Python

Handling files and errors in Python

Posted by Yingshan Li on October 8, 2020

File IN/OUT

The era of genomics has produced a sea of sequencing data. The first thing a bioinformatician needs to do is to read the data into the program. When the analysis is done, the results produced by the program also need to be read out and saved.

读文件

使用open()函数可以打开文件,然后输入参数’r’表示read来告诉python你要读文件

f1 = open("/Users/yingshanli/Desktop/hello.txt", "r")

文件读取成功后,就可以阅读文件中的内容了,根据不同需要可以用不同的方式读取文件内容,

f1.read()	#当文件比较小时,可以一次性读取文件所有内容
f1.read(size)	#可以一次只读取固定字节的内容
f1.readline()	#一次只读取一行
for line in f1.readlines(): #一次性都区所有内容并返回一个list
	... 

记住文件打开之后一定要记得用close()函数关闭

f1.close()

写文件

和读文件一样,首先要用open()函数来打开文件,然后调用”w”(表示write)参数来告诉python你要写文件

f2 = open("/Users/yingshanli/Desktop/hello.txt", "w")

文件读取成功后就可以调用write()函数来写文件了,可以写入一个字符串也可以写入一个列表

f2.write("Hello world!")
f2.write(list)

注意使用”w”参数是,新写入的内容会覆盖原来的内容,如果只是想往文件末尾添加新的内容,可以调用”a”参数(append)

同样打开文件后,最后要记得关闭文件

f2.close()

错误处理与调试

python常见异常类型

  1. NameError: 变量没有声明,name is not defined
  2. ZeroDivisionError: 除数为0, devision by zero
  3. SyntaxError: 语法变量,invalid syntax
  4. IndexError: 索引超过范围,list index out of range
  5. KeyError: 关键字不存在
  6. IOErroe: 输入输出错误,No such file or directory
  7. AttributeError: 访问没有定义的对象属性,x object has no attibute y
  8. ValueError: 数值错误
  9. TypeError: 类型错误

捕获异常

Python的错误处理机制是try…except…finally,当try语句块中出现错误时,程序会跳到except中执行,不管有没有出现错误最后都会执行finally语句块。

for arg in sys.arg[1:]:
	try:
		f = open(arg, "r")
	except IOError as e:
		print("IOError", e)
	else:
		print(arg, "has", len(f.readlines()), "lines")
		f.close

跳过异常

我们能够捕获异常,我们也可以跳过这些异常,让程序不至于中断,而是可以继续进行

for arg in sys.arg[1:]:
	try:
		f = open(arg, "r")
	except IOError as e:
		print("IOError", e)
		pass

定义异常

异常和错误是类,所有的异常类都是从父类BaseException继承下来的,所有的异常都会被它捕获。除了python内置的一些异常类之外,还可以自己选择继承一些异常来定制异常

class FileError(IOError):
	pass
		

抛出异常

我们定义了自己的异常后可以根据需要来抛出异常

for arg in sys.arg[1:]:
	try:
		f = open(arg, "r")
	if arg = "README.txt" :
		raise FileError("Don't open README")