文件和异常 Python

Posted chqworkhome

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了文件和异常 Python相关的知识,希望对你有一定的参考价值。

1、读取文件
with open("F:\\\\1.txt", encoding=const.Utf8) as file:
content = file.read()
file.readline()
lines = file.readlines()
print(content)
等价于
f = open("F:\\\\1.txt", encoding=const.Utf8)
content = file.read()
file.readline()
lines = file.readlines()
print(content)
file.close()
 
补充:python一行写不完?
with open("F:\\\\1.txt", encoding=const.Utf8) as file,\\
open("F:\\\\2.txt", encoding=const.Utf8) as file2:
...
 
2、写文件
with open("F:\\\\2.txt","w", encoding=const.Utf8) as file2:
file2.writelines(lines[:])
file2.writelines(lines)
file.write("")
 
3、文件操作模式
 技术图片
技术图片
 
 
4、文件函数 <class ‘_io.TextIOWrapper‘>
file.readable()
file.writable()
file.encoding //编码方式
file.flush() //刷新
file.tell() //光标当前所在位置
file.seek(n, m) //n:光标移动位置,
//m:默认为0,绝对位置移动;
//m=1:相对位置移动,文件必须以二进制方式打开
//m=2:从末尾绝对位置移动,n为负数
file.truncate(n) //文件保留前n个字符,其余删除
//文件不能以w方式打开,因为一打开内容就会被清空
 
注意:关于光标移动,file.read()函数以字符为单位,其余都是以字节为单位
 
with open("testFile", "rb") as file://循环文件的推荐方式,避免全量读取
for i in file:
print(i)
 
 
5、异常
try:
with open("F:\\\\3.txt") as file:
lines = file.readlines()
except ZeroDivisionError:
print("Error")
raise ZeroDivisionError
except FileNotFoundError:
print("not Found")
else:
print("else")

以上是关于文件和异常 Python的主要内容,如果未能解决你的问题,请参考以下文章

Pythonpython2.7 安装配置OpenCV2

pythonpython-os模块的常用函数

python全栈开发目录

PythonPython获取命令行參数

PythonPython-OpenCV实时处理视频

PythonPython基础