python file-like Object:文件读写
2018-07-23 17:33
861 查看
官网对文件操作解释:
The default mode is
https://docs.python.org/3/library/functions.html#open
文本读写操作:open(), close(), read(), readlines(),
一、普通操作,open(),read(),close()
二、read()完后自动close()
三、为避免read()未知容量的大文件,保险起见用readlines().
四、读二进制文件,如图片,视频等
五、write()
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=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) |
'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
相关文章推荐
- Python:file/file-like对象方法详解【单个文件读写】
- Python 读写文件和file对象(转)
- Python 读写文件和file对象
- python file读写文件笔记
- Python 读写文件和file对象的方法(推荐)
- python判断对象是否为文件对象(file object)
- Python随记(五)文件对象方法 Method of FileObject
- Python 读写文件和file对象
- 在存储过程中用ole对象(Scripting.FileSystemObject)读写文件
- Python 读写当前路径下文件错误 UnboundLocalError: local variable 'file' referenced before assignment
- Python Dict and File -- python字典与文件读写
- python 3.5: TypeError: a bytes-like object is required, not 'str' when writing to a file
- Python文件(File)及读写操作及生成器yield
- 使用Python读取C语言.so文件-: libmysqlclient.so.16: cannot open shared object file: No such file o
- Python 读写文件和file对象的方法(推荐)
- Python之文件与目录操作(os、zipfile、tarfile、shutil)
- Python读写文件实际操作的五大步骤
- Python 3.x Error:TypeError: a bytes-like object is required, not 'str'
- javascript ActiveXObject FileSystemObject 对象,创建、复制、删除、读取文件等
- js用FileSystemObject 对象实现文件控制