File operations
Create a file with the name filename
Content is
BJ
Sh
Gd
TW
Print file Encoding
f = open ("filename", ' R ', encoding= "Utf-8")
Print (f.encoding)
Utf-8
Number of printed in memory
Print(F.fileno ())
3
1. File read Operation 1.1 open () method, mode default read
f = open ("filename", encoding= "Utf-8")
data = F.read ()
Print (data)
BJ
Sh
Gd
TW
1.2 Read the first few lines
f = open ("filename", encoding= "Utf-8")
For I in range (2):
Print (F.readline (). Strip ())
BJ
Sh
1.3 lines are finished reading
f = open ("filename", encoding= "Utf-8")
For I in F:
Print (I.strip ())
BJ
Sh
Gd
TW
1.4 Efficient reading to line X
Count = 0
f = open ("filename", encoding= "Utf-8")
For I in F:
if Count = = 3:
Print ('----------------')
Count + = 1
Print (I.strip ())
Count + = 1
BJ
Sh
Gd
----------------
TW
Ssssss
2. File write operation 2.1 W write mode, if no this file is created
f = open ("Filename2", ' W ', encoding= "Utf-8")
F.write ("Wwwww")
F.close ()
F1 = open ("filename2", encoding= "Utf-8")
data = F1.read ()
Print (data)
F.close ()
Wwwww
2.2 A Append mode
Append at end of file
f = open ("filename", ' a ', encoding= "Utf-8")
F.write ("\nssssss")
F.close ()
BJ
Sh
Gd
TW
Ssssss
2.3 Read + Append mode
f = open ("FileName", "r+", encoding= "Utf-8")
F.write ("\ n------haha------------")
For I in F:
Print (I.strip ())
2.4 File Modification
f = open ("FileName", "R", encoding= "Utf-8")
F1 = open ("Filename1", "W", encoding= "Utf-8")
For line in F:
If "H" in line:
line = line. Replace (' H ', ' G ')
F1.write (line)
F.close ()
F1.close ()
3. Pointer operation
f = open ("filename", encoding= "Utf-8")
Print (F.tell ()) #查看当前指针位置
Print (F.readline ())
Print (F.tell ())
F.seek (0) #指针回到0
Print (F.tell ())
Print (F.readline ())
Print (F.tell ())
0
BJ
4
0
BJ
4
4. Determine if the file can be read and writable
f = open ("filename", ' R ', encoding= "Utf-8")
Print (F.readable ())
Print (F.seekable ())
Print (F.writable ())
True
True
False
5.flush method and Buffer method
f = open ("filename", ' R ', encoding= "Utf-8")
Print (F.flush ()) #从内存写入磁盘
Print (F.buffer)
None
<_io. BufferedReader name= ' filename ' >
6. Implement the progress bar
Import Sys,time
For I in range (10):
Sys.stdout.write ("#")
Sys.stdout.flush ()
Time.sleep (0.5)
##########
7. Truncation
f = open ("FileName", "a", encoding= "Utf-8")
F.seek (0) #指定指针到0的位置
F.write ("123456")
F.truncate (2) #截断2字符
Only 2 characters are reserved in the filename file
BJ
Python Notes-----file operations