One, the file operation
#打开文件需要几步
#1. Open File
F=open (' 1.txt ', ' R ', encoding= ' utf-8 ')
#2. File operation (read or write), manipulate file handle by handle = open (' File path ', ' mode ')
File=f.read ()
#3. Closing files
F.close ()
Second, read the file
F=open (filename,mode,encoding)
# FileName: Indicates file name
# mode: Indicates the format of the open file
# Encoding: Indicates an open encoding format
import CODECSF =codecs.open ( " 1.txt " Span style= "COLOR: #000000" >) text =f.read () print =text.replace ( " 1 ", " a " ) print (Result) # print (F.read ()) print (dir (f)) F.close ()
View Code
#codecs模块只在python2中有, Python3 directly within the Open function (no need to import the module)
Third, File open mode
Common File Open mode:
R: Read-only open, file default open mode
W: file does not exist will be created, if present, overwrite source file (not append)
A: Only append mode is open (cannot read)
r+: Read/write mode (write is append)---> Common
A +: Append read/write
w+: Read-write mode (same as append)----> infrequently used
RB: Binary read mode (generally used for network transmission of data, because the network transmission is based on binary format, so must use B) Python 2.x is can be transmitted with STR
R+b: Open in binary read/write mode
W+b: Open in binary write mode
A+b: Open in binary append and read mode
B: Using binary mode (special files need to be transmitted in text mode, B is recommended)
Encoding Conversion
f = open (' Test.txt ', ' RB ')
F.write (' Hello '. Encoding ())
It can be converted into binary by encoding
Built-in methods for files (Python3)
--for-----> Python 2.x, 3
View Code
f 
=
open
(
' test.txt '
,
' RB '
)
f.write (
hello '
.encoding ())
通过encoding就可以转换成二进制
5 python--file Processing