Python file-like Object: file read/write

Source: Internet
Author: User

Official website to explain the operation of the document:

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



Text Read and write operations: open (), close (), read (), ReadLines (),


One, normal operation, open (), read (), close ()

#!/usr/bin/python#coding=utf-8import loggingtry:f = open ('/home/seeing-zynq/documents/temp/ test/mydict.py ',  ' R ') print f.read ();p rint  ' read ' except exception as e: Logging.exception (e) print  ' ERROR ' raise finally:if f:f.close () print  ' OK ' 

run Result:

#!/usr/bin/python#-*-coding:utf-8-*-class Dict (Dict): Def __init__ (self, **kw): Super (). __init__ (**kw) de F __getattr__ (Self, key): Try:return Self[key] except keyerror:raise attributeerror ( R "' Dict ' object have no attribute '%s '"% key "Def __setattr__ (self, Key, value): self[key] = Valuereadok


Second, read () automatically close after completion ()

with open ('/home/seeing-zynq/documents/temp/test/mydict.py ',  ' r ')  as f:     print  (F.read ()) 

run Result:

#!/usr/bin/python#-*-coding:utf-8-*-class Dict (Dict): Def __init__ (self, **kw): Super (). __init__ (**kw) de F __getattr__ (Self, key): Try:return Self[key] except keyerror:raise attributeerror ( R "' Dict ' object have no attribute '%s '"% key "Def __setattr__ (self, Key, value): self[key] = value



Third, in order to avoid the read () unknown capacity of large files, for insurance purposes with readlines ().

print  '------------------------------------' print  '-----------------------------------' f =  open ('/home/seeing-zynq/documents/temp/test/mydict.py ',  ' R ') For line in f.readlines ( ):     print (Line.strip ())   # #strip会将前面首字符前的空格去掉, resulting in a line sentence without indentation f.close () print  ' Over ' 

Operation Result:

-----------------------------------------------------------------------#!/usr/bin/python#-*-coding:utf-8-*- Class Dict (Dict):d ef __init__ (Self, **kw): Super (). __init__ (**KW) def __getattr__ (self, key): Try:return Self[key] Except Keyerror:raise Attributeerror (r "' Dict ' object have no attribute '%s '"% key) def __setattr__ (self, Key, value): Self[k EY] = Valueover


Four, read binary files, tablets, videos, etc.

>>> f = open ('/users/michael/test.jpg ', ' RB ') >>> f.read () b ' \xff\xd8\xff\xe1\x00\x18exif\x00\x00 ... ' # Hexadecimal representation of bytes


V. 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 

Operation Result:

haha


Python file-like Object: file read and write

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.