广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python file-like Obj
  • 712
分享到

python file-like Obj

pythonfileObj 2023-01-31 05:01:26 712人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

官网对文件操作解释:open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)Charact

官网对文件操作解释:

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

CharacterMeaning
'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()

#!/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'	

运行结果:

#!/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()

with open('/home/seeing-zynq/Documents/Temp/Test/mydict.py', 'r') as f:    
	print (f.read())

运行结果:

#!/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().

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'

运行结果:

------------------------------------
-----------------------------------
#!/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


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

>>> f = open('/Users/michael/test.jpg', 'rb')
>>> f.read()
b'\xff\xd8\xff\xe1\x00\x18Exif\x00\x00...' # 十六进制表示的字节


五、write()

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

运行结果:

haha


--结束END--

本文标题: python file-like Obj

本文链接: https://www.lsjlt.com/news/188548.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作