python文件对象
谢羽白
长风破浪会有时,直挂云帆济沧海
展开
-
利用Python文件对象写个复制图片的脚本
写个复制图片的python脚本:1、下载一张图片到项目的根目录2、读取该图片里的所有文件内容存放到一个全新的图片文件里面#第一种a = open('2.jpeg','rb')b = open('3.jpeg','wb')data = a.read()b.write(data)a.close()b.close()#第二种src_file = '3.jpeg'dst_file = '7.jpeg'a = open(src_file,'rb')b = open(dst_file,'wb原创 2021-02-19 11:09:36 · 153 阅读 · 0 评论 -
Python中的文件指针
seek文件指针:#seek(偏移量,位置) 位置:0表示开头 1表示当前位置 2表示结尾>>> e = open('3.txt','rb') #以rb打开文件文件指针好移动>>> e.read()b'hi\r\nbob\r\nnihao\r\n'>>> e.read()b''>>> e.seek(0,0) #先把文件指针移动到开头然后向右移动0个字节0>>> e.read(2) #从文件指针位置往原创 2021-02-19 11:07:56 · 536 阅读 · 0 评论 -
Python中的with语句
with语句:1、通过with语句来打开文件,with语句结束时,文件会自动关闭>>> with open('3.txt') as e:... e.read()...'hi\nbob\nnihao\n'>>> e.read() #文件已经关闭Traceback (most recent call last): File "<stdin>", line 1, in <module>ValueError: I/O oper原创 2021-02-19 11:06:13 · 101 阅读 · 0 评论 -
python中写入非文本文件
写入非文本文件>>> a = 'hi张三'>>> type(a) #查看数据类型<class 'str'>>>> b = a.encode() #将字符转bytes>>> bb'hi\xe5\xbc\xa0\xe4\xb8\x89'>>> type(b)<class 'bytes'>>>> c = b.decode() #将bytes转字符>>&原创 2021-02-19 11:05:03 · 184 阅读 · 0 评论 -
Python中写入文本文件
6、写入文本文件:>>> e = open('1.txt','w') #文件存在则清空里面的内容>>> e = open('2.txt','w') #文件不存在则会创建>>> e.write('how are you') #向文件里面写入数据11 #写入了11个字节>>> e.flush() #将缓存区里的数据同步到磁盘>>> e = open('3.txt','w') #以w方式打开文件>&g原创 2021-02-19 11:03:46 · 1145 阅读 · 0 评论 -
Python中读取非文本文件的方法
操作文件的步骤(1)打开文件(2)读写文件(3)关闭文件读取非文本文件的方法:>>> e = open('2.jpeg') >>> e.read(5) #python试图将读取到的5个字节转成字符无法转换所以报错了Traceback (most recent call last): File "<stdin>", line 1, in <module>UnicodeDecodeError: 'gbk' codec can't原创 2021-02-19 11:02:24 · 766 阅读 · 0 评论 -
Python中遍历文件的方法
常用来遍历文件的方法:>>> e = open('1.txt','r')>>> for i in e:... print(i,end=' ') #将回车转义成空格...1234567890$%*@:ROOT:BIN qwertyuiopasdfghjkl%&欢迎大家观看我的视频教程:python入门到进阶...原创 2021-02-17 18:04:06 · 125 阅读 · 1 评论 -
Python中读取文本文件的内容
操作文件的步骤(1)打开文件(2)读写文件(3)关闭文件读取文本文件:>>> e = open('2.txt') #以读的方式打开文本文件因为文件路径不存在所以报错Traceback (most recent call last): File "<stdin>", line 1, in <module>FileNotFoundError: [Errno 2] No such file or directory: '2.txt'>>&g原创 2021-02-17 12:37:26 · 505 阅读 · 2 评论