1. File Open
Open mode:
f = open (' Test.txt ', ' R ')
#r, read-only mode, error when file does not exist
f = open (' Test.txt ', ' W ')
#w, write-only mode, the file does not exist when the file is created, when the file exists, empty the original file
f = open (' Test.txt ', ' x ')
#x, Python3 new mode, when the file exists times wrong, file does not exist, create file and write
f = open (' Test.txt ', ' a ')
#a, append mode, file not present, create file
Encoding format:
The above open mode, the default encoding= ' Utf-8 ', when the open file garbled, may be due to inconsistent encoding format caused by
At this point, you can make the file read by adjusting the encoding format
F=open (' Test.txt ', ' R ', encoding= ' utf-8 ')
F=open (' Test.txt ', ' R ', encoding= ' GBK ')
Bytes Mode:
When the b parameter is used, the file opens in bytes, and the file is opened as a character when the B parameter is not applied
F=open (' Test.txt ', ' WB ')
F.write (b ' \xe7\xbb\xbf\xe8\x8c\xb6 ')
F.close ()
= = Write bytes to Test.txt
n = open (' Test.txt ', ' R ', encoding= ' utf-8 ')
t = N.read ()
Print (t)
= = no b parameter, read the file as a character, shown as green tea
2. File operation
F=open (' Test.txt ', ' R ', encoding= ' utf-8 ')
F.seek ()
= = Moves the current pointer position to the specified position, in open mode, when there is no B parameter, is moved by the character position, when opened with the B parameter, the pointer is moved by byte position
F.tell ()
= = Gets the byte position of the current pointer, regardless of the open mode
F.flush ()
+ Strong brush, generally write to the file or modify the operation, is the first cache, when the file is closed and then write to the file, when using the function, directly write the modified content to the file
F.fileno
= = File Descriptor
F.truncate ()
= = truncates all content after the current pointer position
3. File Close
Way One:
F=open (' Test.txt ', ' R ', encoding= ' utf-8 ')
n = f.read ()
F.close ()
Way two:
With open (' Test.txt ', ' R ', encoding= ' utf-8 ') as F:
n =f.read ()
When using with, the close action of the file is automatically
Also, using with can open up to 2 files at a time:
With open (' Test1.txt ', ' R ', encoding= ' utf-8 ') as F, open (' Test2.txt ', ' W ', encoding= ' utf-8 ') as H:
data = F.read ()
H.write (data)