Python file additions and deletions change operation

Source: Internet
Author: User

read and write files (Focus)

# F =open ("Miles", encoding= "Utf-8"). Read ()

# F =open ("Miles",,"a"encoding= "Utf-8") A is append append

will open Miles file, but does not overwrite the previous content, and can then write something

#f =open ("New Miles", "W", encoding= "Utf-8") will create a new file named:new miles, content can be written by
"" "Remember:" W "in Python is a file that overwrites the same name directly, and" R "is the one that reads the file
Read and write must be defined clearly, as shown below, is not readable, can only write
#f =open ("New Miles", "r+", encoding= "utf-8") indicate read and write reading and appending (written at the end)
#f =open ("New Miles", "w+", "encoding=", "utf-8") means that writing a file first, then writing the content
#f =open ("New Miles", "A +", encoding= "Utf-8") indicate an additional read

#f =open ("New Miles", "RB") represents a binary file

cannot be inserted into a line to write, because that will overwrite the contents of the back

"""
F=open ("New Miles","W", encoding="Utf-8")
Data =f.write ("I love Beijing Tian ' an gate")
F.write (" \ n")
Print (data)#此时打印的写入的字符个数

F.close () # Close file s

The number of characters to read can be entered in the read () brackets

Print (F.tell ()) prints the current location

F.seek () means returning to a location

Print (f.encoding) encoding of the printed file

With usage and reasons

If you want to modify a file, use two methods:

1. After you load the files on the hard disk into memory and modify them, the hard disk is re-written.

2. Open a file and re-write to a new file

To prevent the file from shutting down after it has been manipulated, it is handled with the WITH statement

F_new =open ("Miles","W", encoding="Utf-8")

#等价于下面 But the WITH statement is indented below can also be opened at the same time
with open ("Miles","W", encoding="Utf-8") as f_new:

............

Python file additions and deletions change operation

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.