Python file read/write

Source: Internet
Author: User

Open (file, mode= ' R ', Buffering=-1, Encoding=none, Errors=none, Newline=none, Closefd=true, Opener=none)
Open file and return a stream. Raise IOError upon failure.

Common open Mode:

R can only read
R+ is readable and writable, does not create files that do not exist, writes from the top, overwrites content from the previous location
w+ readable writable, if the file exists, overwrites the entire file, does not exist then creates
W can only write, overwrite entire file, not exist then create
A can only be written, add content from the bottom of the file does not exist then create
A + readable writable from the top of the file add content from the bottom of the file does not exist then create??? Actually write from the beginning

Note: RB is binary read, when used to the socket, transfer files, read and write in binary form, RB and WB can be faster file transfer

1 with open (' Test.txt ', mode= ' r+ ', encoding= ' Utf-8 ') as F:2     f.read (1) 3     f.writelines ("Beijing")

============

Write operation does not automatically add line break

There is a line break at the end of the read line and you can remove the line break with the ". Strip ().

With open (' Test.txt ', mode= ' R ', encoding= ' utf-8 ') as F: For    lines in F:        print (Line.strip ()) Remove line break

================

If the pointer is pointing back and you want to read the previous content, you need to first point the pointer back to the front before reading.

With open (' Test.txt ', mode= ' w+ ', encoding= ' utf-8 ') as F:    f.writelines ("Tianjin")    f.writelines (' Shandong ')    F.flush ( )    f.seek (0)    print (F.readlines ())

==============

Example:
f = open (' Cdays-4-test.txt ', ' R ')                   #以读方式打开文件  result = List () for line in  F.readlines ():                              #依次读取每行      line = Line.strip ()                                    #去掉每行头尾空白      if not Len (line) or Line.startswith (' # '):       #判断是否是空行或注释行          Continue                                            # Yes, skip processing      result.append (line)                                #保存  result.sort ()                                               #排序结果   f.close ()    #关闭文件with o Pen (' New_file.txt ', ' W ') as FW:            #with方式不需要再进行close fw.write ('%s '% ' \ n '. Join (Result)) #保存入结果文件

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