When programming in Python, we often need to view local files or save data, which requires the use of functions and methods provided by Python to open and close files and read and write files.
In python, use the open function to open an existing file or create a new file.
The syntax is as follows:
"F = open('file path', mode='mode to open file', encoding='character encoding of operating file')"
Common file opening modes
After the operation of the file is over, use close() to close the file.
f =open('a.txt',mode='r',encoding='utf-8')
# read()Read the entire file, usually put the contents of the file into a string variable;
xx = f.read()print(xx)
f.close()
Of course, there is an easier way, which does not need to close the file every time.
withopen('a.txt','r')as files:
content=files.read()print(content)
After using the keyword with, there is no need to close the file after accessing it. Python will automatically close it when appropriate, so as to avoid the bug that the file will not be closed because the close() statement is not executed.
Python opens the file and reads the content in three ways:
read(num): indicates the length of the data to be read from the file (in bytes), if num is not written, it means reading all the data in the file.
readline(): read one line of content at a time;
**readlines(): ** You can read the contents of the entire file at once in a line-by-line manner, and return a list, in which the data of each line is an element.
**1. write(str): Write the string str to an open file. **
**If the file you want to write does not exist, the function open() will automatically create it. We use the method write() of the file object to write a string to the file. **
**Write the string "I Love Python" into the file a.txt. **
withopen('a.txt','w')as files:
files.write("I Love Python.")withopen('a.txt','r')as files:
content=files.read()print(content)
Output:
I Love Python.
The function write() will not add a newline at the end of the text you write, you need to add it manually\n
**2. The parameter of file.writelines(sequence) is a sequence, such as a list, which will iteratively write the file for you. **
File a.txt, content abcd, file b.txt, content ABCD
**Append file a to file b. **
withopen('E:/a.txt','r')as file1:withopen('E:/b.txt','a+')as file2:
file2.writelines(file1.readlines())withopen('E:/b.txt','r')as files:
content=files.read()print(content)
Output:
ABCDabcd
Recommended Posts