Home >Backend Development >Python Tutorial >How to read a file into an array line by line
The Python open() method is used to open a file and return a file object. This function needs to be used during file processing. If the file cannot be opened, an OSError will be thrown.
Note: When using the open() method, you must ensure that the file object is closed, that is, the close() method is called.
The common form of the open() function is to receive two parameters: file name (file) and mode (mode).
#How to read a file into an array line by line?
Use readlines() to read all lines and return a list.
Encoded in utf-8, open the file in read-only mode (the text file is saved in Chinese).
Full code:
with open(r'D:/test.txt','r',encoding='utf-8') as file: content_list = file.readlines() #读取所有行并返回列表 contentall = [x.strip() for x in content_list] print(contentall)
Use for A line of statements, after removing the leading and trailing spaces, add it to the array
The above is the detailed content of How to read a file into an array line by line. For more information, please follow other related articles on the PHP Chinese website!