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