Catalog
File read and write
Read the file
IOError exception handling
UnicodeDecodeError exception handling
Writing documents
File operation method
The function of reading and writing files on disk is provided by the operating system , The modern operating system does not allow ordinary programs to operate the disk directly , therefore , To read and write a file is to ask the operating system to open a file object ( Usually called a file descriptor ), then , Read data from this file object through the interface provided by the operating system ( Reading documents ), Or write the data to the file object ( Writing documents ).
Use Python Built in open()
function , Pass in the filename and identifier , identifier 'r' Express reading .
f=open('F:\eclipse\eclipse\sy9T3.txt','r')
If the file does not exist, it will throw FileNotFoundError.
After successfully opening the file , call read() Methods read all the contents of the document at one time .
f.read();
Last call close() Method to close the file. The file must be closed after use , Because file objects take up operating system resources , And the operating system can open a limited number of files at the same time .
f.close()
In order to avoid too much content , Call again and again read(size)
Method , Read at most each time size Bytes of content .
among readline()
You can read one line at a time , call readlines()
Read everything at once and return... By line list
.
IOError
exception handling Because it is possible to produce IOError
, Once the error , hinder f.close()
Will not call . therefore , In order to ensure that the file can be closed correctly whether there is an error or not , We handle exceptions in advance :
Method 1 :
try...finally
try:
f = open('/path/to/file', 'r')
print(f.read())
finally:
if f:
f.close()
Method 2 :
introduce with
with open('/path/to/file', 'r') as f:
print(f.read())
The second method is more concise , And you don't have to call f.close()
Method .
read() May throw UnicodeDecodeError(encoding No matter how it is used utf8、gb2312、gbk The coding method is not good )
terms of settlement :
Read in binary mode instead :open('xxx.xsl','rb')
f=open('F:\eclipse\eclipse\sy9T3.txt','rb')
f.read()
Writing a file is the same as reading a file , The only difference is to call open()
Function time , Passed in identifier 'w'
perhaps 'wb'
To write a text file or binary file :
f=open('F:\eclipse\eclipse\sy.txt','w')
f.write("I love Python!")
f.close()
After the above operations , Click open file
notes :1. Only a call close()
When the method is used , Only the operating system can ensure that all the data not written is written to the disk .
2. With 'w'
When mode writes to a file , If the file already exists , Will directly cover ( Equivalent to deleting and writing a new file ).
You can pass in 'a'
To add (append) Mode writing Append to end of file
f=open('F:\eclipse\eclipse\sy.txt','a')
f.write("end")
f.close()
List of articles effect Code
List of articles One 、 downlo