File read and write operations --open () function to read and write files 01

Reprinted: https://www.cnblogs.com/thebear/p/9560939.html

"" " Read Files " "" 
# Open () function to open a file object, the incoming file name (path) and the identifier (read, write and other operations) 
# 'R & lt' identifier indicated 'read' 
# Read () method once read the entire contents of the file, expressed as a str 
# last call close () method to close the file, and there must be close () method 
>>> file = " /tmp/pt.txt " 
>>> f = Open (file , ' R & lt ' )  
 >>> reached, f.read ()
 ' 123 \ n- ' 
>>> f.close () 

# when the file is generated write Error, behind f.close () will not be called, so Error can guarantee whether or not properly close the file 
# with statement automatically calls the close () method 

[root @ the WWW PythonTest] # CAT FileRead.py
#!/usr/bin/python3.6
#- * - UTF-Coding. 8 - * - 
File = " /tmp/pt.txt " 
with Open (File, ' R & lt ' ) AS F:
     Print (reached, f.read ()) 

# call read () to read a one-time all contents of the file, which is obviously not practical, if large files, memory collapsed 
# the read (size) method each read up to size bytes of content. The file size can not be determined, repeatedly call read (size) suitable to 
# the readline () method reads every single line. 
# Readlines () method to read all the content once and press OK to return list. If the configuration file, call readlines () the most convenient 

[root @ the WWW PythonTest] # vim fileread.py 
# /usr/bin/python3.6! 
# - * - Coding UTF-8 - * - 

File = " / tmp / pt .txt " 
F = Open (File, 'R & lt ' ) 

for Line in f.readlines ():
     Print (line.strip ())   # Strip () remove newline \ n- 
    
f.close () 

# read a binary file, such as pictures, video, etc., using' rb ' open the file mode 
>>> = file " /tmp/test.png " 
>>> F = open (file, ' RB ' )
 >>> reached, f.read () >>> = file " /tmp/test.png " 
# when reading non utf-8 encoded text files, need to open () function passing the encoding parameter 
>>> F = Open (file, ' R & lt ' , encoding = ' GBK ')
 # When faced with non-standard file encoding, you can open () function parameter passing errors, indicate how to deal with after an error
F = Open >>> (File, ' r ' , encoding = ' GBK ' , errors = ' the ignore ' )   # represents encountered an error to ignore 


"" " write file " "" 
# write files and read documents is the same, the only The difference is call open () function, the incoming identifier 'w' or 'wb' for write text files or write binary file 
# the write () method to write the file 
# finally call close () method to close the file, and there must be close () method 
# when 'w' mode written to the file, if the file exists, will be used to cover the default 
# if you want to use additional way to use 'a' or 'a +' parameter. they are added from the end of file 
[root @ PythonTest the WWW] # vim filewrite.py 
# ! / usr / bin / python3.6
# -*- coding utf-8 -*-
file = "/tmp/pt.txt" 
F = Open (File, ' W ' )   # additionally using Open = F (File, 'A') 
f.write ( " Hello, Word \ n- ' ) 
f.close () 

"" " write summary " "" 
open () function parameters 
open (filename, the mODE, bufsize, encoding, errors, NEWLINE, closefd) 
filename # to open the folder names. for example /tmp/pt.txt 
the mODE      # file open mode, operating mode list see below 
the bufsize of   # buffer size. 0 indicates when to open the file without buffering, buffering is expressed. 1 
encoding # file encoding type. = e.g. encoding 'GBK' 
errors    # error handling. = e.g. errors 'the ignore' 
NEWLINE   #Common mode control line break behavior, line breaks between the different os inconsistent 
closefd () # control file is completely shut off when the document 

file operators (open mode), the operator may be combined 
R & lt # Read (default ) 
W # writable 
a # additional data 
B # binary data pattern, such as pictures, video, etc. 
X # Create a new file and may be written, for example, open (file, 'x') , written directly write () function can be 
+ # open the file directly to update 
t # text mode (default) 

file operations 
the read ()       # read 
readline ()   # read line 
readlines () # the entire file by line read into the list of 
the write ()      # write 
writelines () # to the file writes a list of rows of data
close ()      # close the file, open () a file you must close a file 

using a while loop to read the statement lines in the file 

# /usr/bin/python3.6! 
# - * - Coding UTF-8 - * - 
File = ' /tmp/pt.txt ' 
F = Open (file, ' R & lt ' )
 the while True: 
    Line = f.readline ()
     IF  Not Line:
         BREAK 
    Print (Line) 
f.close () 

using an iterative loop for file All the rows 
for line in F:
     Pass 
    
    
processing data in the file example: 

[pythontest the root @ localhost] # CAT /tmp/pts.txt
2 
[pythontest the root @ localhost] # CAT exampletest.py 
# /usr/bin/python3.6! 
# - * - UTF-Coding. 8 - * - 

DEF file_hd1 (name = ' /tmp/pts.txt ' ):   # define a document processing function 
    F = open (name)                   # open file 
    RES = 0                          # accumulator variable RES 
    I 0 =                            # rows variable I 

    for line in F:                   # line file iteration 
        I + =. 1 Print ( ' % s of data line is: ' %
        line.strip (), Line) 
        RES + = int (Line)             # accumulated data for each line 

    Print ( ' these numbers and to: ' , RES)      # print data and 
    f.close ()                        # close the file 

IF  the __name__ == ' __main__ ' : 
     file_hd1 ()                      # call the function 
[pythontest the root @ localhost] # python3.6 exampletest.py 
data row is 1: 1 

data line 2 is: 2 

rows of 3: 3 

of these numbers and is: 6 "" " StringIO " "" #



 Sometimes, the data read and write is not necessarily a file, you can also read and write in memory 
 # "StringIO" means that reading and writing in memory str 
 # StringIO operation can only be str 
>>> from IO Import StringIO
 >>> f = the StringIO ()
 >>> f.write ( ' Hello ' )
 >>> f.write ( '  ' )
 >>> f.write ( ' . 1 ' )
 >>> Print (f.getvalue ()) 
Hello   . 1 # by str initialization StringIO, realized in units read 
[root @ the WWW PythonTest] # CAT fileIO.py 
# ! / usr / bin / python3.6
# -*- coding utf-8 -*-from
 


IO Import the StringIO 
F = the StringIO ( ' !!! Hello \ NHI \ nbyebye ' )
 the while True: 
    S = f.readline ()
     IF S == '' :
         BREAK 
    Print (() s.strip) 

# output 
[root @ PythonTest WWW] # python3.6 fileIO.py 
Hello! 
Hi! 
byebye! 


"" " BytesIO " "" 
# to operate the binary data, it is necessary to use BytesIO 
# than a string written, but after utf-8 encoded bytes
 
>>> from IO Import BytesIO
 >>> F =BytesIO ()
 >>> f.write ( ' Chinese ' .encode ( ' UTF-. 8 ' ))
 >>> Print (f.getvalue ()) 
B ' \ XE4 \ XB8 \ XAD \ XE6 \ X96 \ the x87 ' 
# It can be initialized with a BytesIO bytes, then read the same file as read 
>>> from IO Import BytesIO
 >>> BytesIO F = (B ' \ XE4 \ XB8 \ XAD \ XE6 \ X96 \ the x87 ' )
 >>> F. Read () 
B ' \ XE4 \ XB8 \ XAD \ XE6 \ X96 \ the x87 '

 

Guess you like

Origin www.cnblogs.com/xiaobaibailongma/p/12375539.html