File reading and writing is the most basic and common operation , This article mainly introduces the use of Python To read and write files , Realize automatic operation of files .
Python Provide open Function to read and write files , Files can be manipulated at any time . Let's explain first open Function usage , Then I will write several examples of file reading and writing .
Python open() Method is used to open a file , And return the file object , This function is used for processing files , If the file cannot be opened , Will throw out OSError.
Be careful : Use open() Methods must ensure that the file object is closed , That is to call close() Method .
Python It also provides a way to automatically close files , stay open Before using with, There is no need to call close Method . We usually use this method , such as :
with open("file_name.txt", "r") as fr:
pass
You only need to open the file object fr To operate , There is no need to think about when close file .
open() A function usually takes two arguments : file name (file) And pattern (mode). such as :
with open(file, mode='r') as fr:
pass
Here we introduce some common parameters :
r
Open the file read-only . The pointer to the file will be placed at the beginning of the file . This is the default mode .
w
Open a file only for writing . Open the file if it already exists , And edit from the beginning , The original content will be deleted . If the file does not exist , Create a new file .
a
Open a file for appending . If the file already exists , The file pointer will be placed at the end of the file . in other words , The new content will be written after the existing content . If the file does not exist , Create a new file to write to .
Use open Function to open file Object we can read and write , Here are some read / write functions :
file.read([size])
Read the specified number of bytes from the file , Read all if not given or negative .
file.readlines([sizeint])
Read all the lines and return the list , If given sizeint>0, Set how many bytes to read at a time , This is to reduce the reading pressure .
file.write(str)
Write string to file , What is returned is the length of the characters written .
Let's see how to use python Code implementation file reading .
1. Use read() Read out the contents of the file at one time .
def read_file(file_name):
"""
Read the file , Return the contents of the file
"""
with open(file_name, "r", encoding="utf-8") as fr:
contents = fr.read()
return contents
2. Use readlines() Read all the lines and return the list , Each element of the list corresponds to each line of the file
def read_file_by_lines(file_name):
"""
Read the file by line , Returns a list of strings per line of the file
"""
with open(file_name, "r", encoding="utf-8") as fr:
content_lines = fr.readlines()
return content_lines
Next let's see how to use Python The code implements the writing of files :
def save_file(file_name, contents):
"""
take contents The content is saved in the corresponding file_name file
"""
with open(file_name, "w", encoding="utf-8") as fw:
fw.write(contents)
actual combat :
if __name__ == "__main__":
content_str = "I love python, I am studying python file operate"
files_name = "file_operation.txt"
# hold content_str write file file_operation.txt
save_file(files_name, content_str)
# Read the file , Return string
content = read_file(files_name)
print(content)
# Read the file by line , Returns a list of strings per line
content_list = read_file_by_lines(files_name)
print(content_list)
Execution results
I love python, I am studying python file operate
['I love python, I am studying python file operate']
Expand :
There are many modes for reading and writing files , You can set the mode according to your own needs , But the above introduction is the most basic reading and writing , After mastering , Other models are the same .
open The open file object , In addition to the three functions described above , There are other functions that can be used , If you are interested, you can check , Master the above three basic usages , Everything else is simple , The lines .