Python The function of reading and writing files is built in The core ： Reading and writing files actually requests the operating system to open a file object 【 File descriptor 】
step ： a. Open file ：open() b. Read file contents ：read() c. Close file ：close() Be careful ： Remember to close the file after using it , Because file objects will occupy the system resources of the operating system , And the number of files opened by the operating system in the same period of time is limited , In order to avoid the waste of resources .
For your understanding , Let's talk about the specific parameters ：
""" open(path,flag,[encoding,errors]) path: Path to file 【 Absolute path and relative path 】 flag: How to open a file r: read-only rb: Open the file in binary format , read-only r+: Reading and writing w: Write only wb: Write to file in binary format , If the file already exists, override , If not, create a new file w+: Reading and writing a:append, If something already exists in a file , The new content will be added after the original content encoding： Coding format ,utf-8,gbk errors: Error handling """
One 、 Open file
path = "C:/Users/jiejie/Desktop/ To oak .txt" #r： Open the file as read-only f = open(path,"r",encoding="gbk") """ Be careful 1： When we use r When opening a file in the form of ： If the file format is gbk Of , Can not add encoding = "gbk" If the file format is utf-8, Must be added encoding = "utf-8" Be careful 2： Binary format is generally used to process pictures , video , Audio If the document is rb perhaps wb Open in the form of , Can not add encoding, Will report a mistake encode(): code decode(): decode """
Two 、 Read the file
#1. Read all ************ str = f.read() print(str) #2. Reads the specified number of characters # If every line ends with a "\n" Symbol , Also known as characters str1 = f.read(2) print(str1) #3. Read entire line , No matter how many characters the line has ********** # Call to read one line at a time , After reading a line , Move the cursor of the operation file to the beginning of the next line str2 = f.readline() print(str2) str2 = f.readline(3) # Read... In one line 3 Characters print(str2) #4. Read everything out , Return a list , Each row of data is an element result = f.readlines() print(result) 3、 ... and 、 Close file f.close() Next, let's apply it briefly , Abbreviation ： path = " To oak .txt" # Shorthand way # benefits ： You don't need to do it manually close, Avoid the waste of resources caused by forgetting to close the file with open(path,"r",encoding="gbk") as f: result = f.read() print(result) try: f1 = open(path,"r",encoding="gbk") print(f1.read()) except FileNotFoundError as e: print(" file does not exist ",e) except LookupError as e: print(" Unknown encoding specified ") except UnicodeDecodeError as e: print(" Read file decode error ",e) finally: if f1: f1.close()
step ： a. Open file b. Write information to the cache c. Refresh file internal buffer 【 Improve the efficiency of writing 】 d. Close file Be careful ： If the file to write the content doesn't exist , A file is automatically created
path = "file11.txt" #1. Open file f = open(path,"w",encoding="utf-8") #2. Write content , Write the content to the buffer f.write("Whatever is worth doing is worth doing well The bank is very proud, very critical ") #3. Refresh buffer 【 Speed up the flow of data , Keep the buffer flowing 】 f.flush() #4. Close file f.close()
Shorthand way ： You don't have to call it manually close with open(path,"w",encoding="utf-8") as f1: f.write("Whatever is worth doing is worth doing well The bank is very proud, very critical ")
Encoding and decoding
String type and byte type conversion process String type to byte type ： code ,encode Byte type to string type ： decode ,decode
str = " Today is a good day today is a good day" path = "C:/Users/jiejie/Desktop/file22.txt" with open(path,"wb") as f: result = str.encode("utf-8") print(result) f.write(result) with open(path,"rb") as f1: data = f1.read() print(data) print(type(data)) newData = data.decode("utf-8") print(newData) print(type(newData))
practice ： Copy files
demand ： Realize the copy of file content Ideas ： Source file ： Read it out Target file ： Write to
import os def myCopy(srcPath,desPath): #1. Determine whether the source file exists if not os.path.exists(srcPath): print(" Brother , file does not exist , Don't copy it ") return #2. Determine whether the source file is a file type if not os.path.isfile(srcPath): print(" It's not a document , Cannot copy ") return #3. Open source and target files srcFile = open(srcPath,"rb") desFile = open(desPath,"wb") #4. Get the size of the source file size = os.path.getsize(srcPath) while size > 0: # Read content = srcFile.read(1024) # write in desFile.write(content) size -= 1024 #5. Close file srcFile.close() desFile.close() myCopy("file11.txt","file22.txt")
summary ： Above we have explained the knowledge of file reading and writing , Reading documents , Writing documents , And about the various parameters , Encoding and decoding of files , Finally, there is a copy of the contents of the file , If you are interested, you can press to operate it ！ Welcome to discuss with you ~~~
That's all for today's sharing ~ Welcome to discuss ~~~
This article is from WeChat official account. - Data Valley （BigDataValley）
The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the email@example.com Delete .
Original publication time ： 2021-01-15
Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .