在python对文件操做用的是open
函数,其通常使用形式是f = open(file, encoding,mode)
。file
是文件路径,encoding
是文件编码,mode
是打开文件的模式,f
称为文件句柄。
通常的文件编码有:html
默认以操做系统的编码方式打开python
打开文件的模式有:git
模式 | 符号 |
---|---|
读 | r |
写 | w |
追加 | a |
字节形式 | b |
文本形式 | t |
更新(可读可写) | + |
默认mode="rt"github
读取文件的方法有一下几个:windows
一些与读取相关的方法:markdown
假若有这样一个文件(./test.txt
):dom
test file line1 test file line2 test file line3
使用open例子:函数
f = open("./test.txt", mode="r", encoding="utf-8")
print(f.readable()) # True
print(f.read())
print(f.tell()) # 49 # 查看光标位置
f.seek(0) # 把光标放到开头位置
print(repr(f.readline())) # 'test file line1\n'
print(f.readlines()) # ['test file line2\n', 'test file line3']
f.close() # 关闭文件
print(f.closed) # True
直接用open操做文件时,不要忘了使用close()方法关闭文件编码
seek补充
seek方法有三种模式,用第二个参数的值肯定。spa
注意:非默认模式(1
或2
)时,Python 要求文件必需要以二进制格式(b
)打开,不然会抛出io.UnsupportedOperation
错误。
例子
# test.txt有44个字符
f = open("./test.txt", mode="rb")
f.seek(10, 0) # 默认形式,以绝对位置
print(f.tell()) # 10
f.seek(10, 1) # 相对位置,往前移10个字符
print(f.tell()) # 20
f.seek(-10, 2) # 从文件尾部开始移动,注意数值是负数的
print(f.tell()) # 34
f.close()
使用写的方法会把原文件清空而后从新写入,一样先列出其相关方法:
例子:
f = open("./test.txt", mode="w", encoding='utf-8')
print(f.writable())
f.write("new line1\n")
f.writelines(["new line2\n", "new line3\n"])
f.close()
写的时候写入字符串或字节类型(根据mode参数而定)
f = open("./test.txt", mode="w", encoding='utf-8')
f.write("new line1\n")
f.close()
# 字节方式
f = open("./test.txt", mode="bw")
f.write("new line2\n".encode('utf-8'))
f.close()
追加,即在原文件的尾部写入。
f = open("./test.txt", mode="a", encoding='utf-8')
print(f.tell()) # 33 # 在最后
f.write("new line4\n")
f.close()
open支持上下文管理协议,便可以与with函数结合使用,使用with函数,咱们就不须要在最后使用close()
方法,手动将文件关闭了。
with open("./test.txt", "r", encoding='utf-8') as f:
print(f.read())
python使用try-except-else-finally
的形式处理异常,通常来讲,经常使用的格式是try-except
,try
中写正常的逻辑代码,而except
中写处理异常的代码。else
表示try中代码不出错时执行;finally
中的代码无论出不出错多执行,能够在这里写释放资源等的代码。
例子一:
try:
print(1234)
raise Exception("手动触发的异常")
except Exception as e:
print(e) # 手动触发的异常
finally:
print("finally执行了")
例子二:
try:
print(1234)
#raise Exception("手动触发的异常")
except Exception as e:
print(e) # 手动触发的异常
else:
print("正常执行了")
finally:
print("finally执行了")
在python内部有一些内置的异常类,通常来讲咱们能够直接使用他们,假如是特殊的状况,咱们能够继承其中一个类,本身自定义异常类。
自定义异常类例子:
class NumError(ValueError):
"""输入小于0参数的异常类"""
def __init__(self, num):
# 写你须要的参数
self.num = num
def __str__(self):
# 描述信息
return "数值不能小于0,你输入的数值为%d" % self.num
def test(num):
if num > 0:
print("processing ....")
else:
raise NumError(num) # 手动抛出异常
def main():
test(2)
test(-1) # __main__.NumError: 数值不能小于0,你输入的数值为0
if __name__ == '__main__':
main()