前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >python file-like Obj

python file-like Obj

作者头像
py3study
发布于 2020-01-07 12:00:41
发布于 2020-01-07 12:00:41
99400
代码可运行
举报
文章被收录于专栏:python3python3
运行总次数:0
代码可运行

官网对文件操作解释:

open(filemode='r'buffering=-1encoding=Noneerrors=Nonenewline=Noneclosefd=Trueopener=None)

Character

Meaning

'r'

open for reading (default)

'w'

open for writing, truncating the file first

'x'

open for exclusive creation, failing if the file already exists

'a'

open for writing, appending to the end of the file if it exists

'b'

binary mode

't'

text mode (default)

'+'

open a disk file for updating (reading and writing)

'U'

universal newlines mode (deprecated)

The default mode is 'r' (open for reading text, synonym of 'rt'). For binary read-write access, the mode 'w+b' opens and truncates the file to 0 bytes. 'r+b' opens the file without truncation.

https://docs.python.org/3/library/functions.html#open

文本读写操作:open(), close(), read(), readlines(),  

一、普通操作,open(),read(),close()

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#!/usr/bin/python
#coding=utf-8

import logging

try:
	f = open('/home/seeing-zynq/Documents/Temp/Test/mydict.py', 'r')
	print f.read();
	print 'read'
except Exception as e:
	logging.exception(e)
	print 'error'
	raise 
finally:
	if f:
		f.close()
		print 'OK'	

运行结果:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#!/usr/bin/python
# -*- coding: utf-8 -*-

class Dict(dict):

    def __init__(self, **kw):
        super().__init__(**kw)

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(r"'Dict' object has no attribute '%s'" % key)

    def __setattr__(self, key, value):
        self[key] = value





read
OK

二、read()完后自动close()

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
with open('/home/seeing-zynq/Documents/Temp/Test/mydict.py', 'r') as f:    
	print (f.read())

运行结果:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#!/usr/bin/python
# -*- coding: utf-8 -*-

class Dict(dict):

    def __init__(self, **kw):
        super().__init__(**kw)

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(r"'Dict' object has no attribute '%s'" % key)

    def __setattr__(self, key, value):
        self[key] = value

三、为避免read()未知容量的大文件,保险起见用readlines().

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
print '------------------------------------'
print '-----------------------------------'
f = open('/home/seeing-zynq/Documents/Temp/Test/mydict.py', 'r')
for line in f.readlines():
    print(line.strip())  ##strip会将前面首字符前的空格去掉,造成行句没有缩进
f.close()
print 'over'

运行结果:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
------------------------------------
-----------------------------------
#!/usr/bin/python
# -*- coding: utf-8 -*-

class Dict(dict):

def __init__(self, **kw):
super().__init__(**kw)

def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Dict' object has no attribute '%s'" % key)

def __setattr__(self, key, value):
self[key] = value




over

四、读二进制文件,如图片,视频等

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> f = open('/Users/michael/test.jpg', 'rb')
>>> f.read()
b'\xff\xd8\xff\xe1\x00\x18Exif\x00\x00...' # 十六进制表示的字节

五、write()

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
with open('/home/seeing-zynq/Documents/Temp/IO/a.txt', 'w') as f:   
    f.write('haha')

with open('/home/seeing-zynq/Documents/Temp/IO/a.txt', 'r') as f:  
    print (f.read())
"file.py" 37L, 758C wri

运行结果:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
haha
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档