python files to read

--- --- restore content begins

r mode, read-only mode, can not be written, the file does not exist will be given

# R mode, can read but not write, the file does not exist will complain 
f = Open ( ' a1.txt ' ) # do not write 'r', the default read only 
the Result = f.readlines () # readlines read all, it is a list of 
f.seek (0) # file pointer returns to the first row 
RESULT1 reached, f.read = () # read to read all, it is a string 
f.seek (0) 
result2 = f.readline () # each row read only 
result3 f.readline = () # each row read only 
result4 f.readline = () # each row read only 

f.close () 
Print (Result)
 Print (RESULT1)
 Print (result2)
 Print (result3)
 Print (result4)

Output: 
[ ' first line \ n- ' , ' second line \ n- ' , ' third line ' ] 
of the first row 
of the second row 
the third row 
of the first line of 

the second row 

the third row
#w mode, can not read the writing, the file does not exist will complain, will clear the previous contents (scratch editor)
# W mode, can not read the writing, the file does not exist will complain, will clear the previous contents (scratch editor) 
S = [ ' abc ' , ' BCD ' , ' cdbd ' ] 
f = Open ( ' a2.txt ' , ' W ' , encoding = ' UTF-. 8 ' ) 
RESULT1 = f.write ( ' ABC \ n- ' ) # Write string can pass 
result2 = f.writelines (S) # the writelines can pass type may be a loop, dictionaries, lists, etc. 
f.close ()

r + mode, can read and write, there is no file will complain, will not clear the file, the file pointer at the beginning

# R & lt + mode, can be read or write but will be given a file does not exist, the file is not empty, the pointer on the file header, 
F = Open ( ' a2.txt ' , ' R & lt + ' , encoding = ' UTF-. 8 ' ) 
Result = reached, f.read () 
f.write ( ' r + append ' ) 
f.close () 
Print (Result) 

outputs: 
a first row 
R & lt + r + additionally added

w + mode, the pointer on the end, can read and write, but not read something that will clear the file

# W + mode, can be read or write, can not read after writing things, will clear the file, the pointer placed at the end 
F = Open ( ' a2.txt ' , ' W + ' , encoding = ' UTF-. 8 ' ) 
Result = reached, f.read () 
f.write ( ' R & lt append + ' ) 
f.close () 
Print (Result)

a + mode, can read and write, can be added is not empty, the pointer at the beginning, not reproduce something

# A + mode, can read or write, can not read after writing things, the file is not empty, the pointer at the end of finished 
F = Open ( ' a2.txt ' , ' A + ' , encoding = ' UTF-. 8 ' ) 
f.seek (0) # pointer can be placed at the beginning of things read 
Result = reached, f.read () 
f.write ( ' a + append mode ' ) 
f.close () 
Print (Result) 

output: 
a + append mode

 

--- end --- restore content

Guess you like

Origin www.cnblogs.com/mhmh007/p/11598372.html