Python IO Programming--File read/write

Source: Internet
Author: User

1.1   file read/write1.1.1   Read the file

>>> f = open ('/root/python/hello.py ', ' R ') # identifier r denotes read

>>> f =open ('/root/python/hello1.py ', ' R ') # file does not exist error

Traceback (most recent):

File "<stdin>", line 1, in <module>

Filenotfounderror: [Errno 2] No such fileor directory: '/root/python/hello1.py '

Read File contents

>>> f.read () #str Object

"#!/usr/bin/python\nprint (' Hello,world ') \ n"

>>> F.close () # Close File

file invocation may result in read and write IOError, once the error F.close () will not be called, then we use the following statement:

>>> Try:

... f = open ('/root/python/hello.py ', ' R ')

... print (F.read ())

... finally:

... if f:

... f.close ()

...

#!/usr/bin/python

Print (' Hello,world ')

Python provides us with a much simpler approach.

>>> withopen ('/root/python/hello.py ', ' R ') as F:

... print (F.read ())

...

#!/usr/bin/python

Print (' Hello,world ')

Attention:

Read () reads the entire contents of the file at once, using smaller files;

Read (size) reads the contents of a size byte at most, and does not determine the size of the file;

ReadLine () can read one line at a time, call ReadLines () to read all the content at once and return the list by row , for the configuration file.

>>> withopen ('/root/python/hello.py ', ' R ') as F:

... For line in F.readlines ():

... print (Line.strip ())

...

#!/usr/bin/python

Print (' Hello,world ')

1.1.2   File-like Object

like the Open () function , this object, which has a read () method, is called File-like object in Python. file-like Object does not require inheritance from a particular class, just write a read () method on the line.

1.1.3   Binary Files

The default is to read the text file, and it is a UTF-8 encoded text file. To read binary files, compare slices, videos, etc., open the file with ' RB ' mode.

>>> f =open ('/users/michael/test.jpg ', ' RB ')

>>> F.read ()

B ' \xff\xd8\xff\xe1\x00\x18exif\x00\x00 ... ' # hexadecimal representation of bytes

1.1.4   character encoding

to read non- UTF-8 encoded text file, need to give the open () function incoming encoding parameter, for example, read GBK encoded file:

>>> f =open ('/users/michael/gbk.txt ', ' R ', encoding= ' GBK ')

>>> F.read ()

' test '

You may encounter some files that are not code-compliant Unicodedecodeerror, because there may be some characters that are illegally encoded in a text file. In this case,the open () function also receives a errors parameter that indicates what to do if a coding error is encountered. The simplest way is to ignore it directly:

>>> f =open ('/users/michael/gbk.txt ', ' R ', encoding= ' GBK ', errors= ' ignore ')

1.1.5   Write a file

Python does not require the destination file to exist when writing files.

[[email protected] python]# ls test.txt

Test.txt

[Email protected] python]# rm-f test.txt

[[email protected] python]# python

Python 3.5.0b4 (default, Jul 1 2016, 21:28:36)

[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] Onlinux

Type "Help", "copyright", "credits" or "license" for moreinformation.

>>> f = open ('/root/python/test.txt ', ' W ') #w means write text file,WB means write binary file

>>> f.write (' hello,python! ')

14

>>> F.close ()

>>>

[email protected] python]# cat Test.txt

Hello, python!.

Write again on the same file will overwrite

>>> withopen ('/root/python/test.txt ', ' W ') as F: # can also encoding specified character encoding

... f.write (' abc ')

... f.write (' 123 ')

...

3

3

>>>

[Email protected] python]#

[email protected] python]# cat Test.txt

abc123 [[email protected] python]# python

Python 3.5.0b4 (default, Jul 1 2016, 21:28:36)

[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] Onlinux

Type "Help", "copyright", "credits" or "license" for moreinformation.

>>> withopen ('/root/python/test.txt ', ' W ') as F:

... f.write (' NEW ')

...

3

>>>

[Email protected] python]#

[email protected] python]# cat Test.txt

NEW


This article is from the "90SirDB" blog, be sure to keep this source http://90sirdb.blog.51cto.com/8713279/1826523

Python IO Programming--File read/write

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.