Home >Backend Development >Python Tutorial >What three methods does python provide for reading the contents of text files?
The three methods are: "read()", "readline()", and "readlines()". "read()" reads all the contents of the file at once and puts it into a large string; "readline()" reads the text line by line; "readlines()" reads all the contents of the text at once.
There are three methods for python to read the contents of a text file.
read(), readline(), readlines()
read()
read() It is the simplest method to read all the contents of the file at once and put it in a large string, that is, in memory.
file=open('test.txt')try: file_context=file.read() #file_context是一个string,读取完后,就失去了对test.txt的文件引用 #file_context=open(file).read().splitlines(),则 #file_context是一个list,每行文本内容是list中的一个元素finally: file.close()12345678
Advantages of read(): convenient, simple, one-time reading of the file into a large string, the fastest.
Disadvantages of read(): When the file is too large, it will occupy too much memory
readline()
readline() one by one Read text line by line, the result is a list
with open(file) as f: line=f.readline() while line: print line line=f.readline()12345
Advantages of readline(): small memory usage, read line by line
Disadvantages of readline(): read line by line, The speed is relatively slow
readlines()
readlines() reads all the contents of the text at once, and the result is a list
with open(file) as f: for line in f.readlines(): print line#这种方法读取的文本内容,每行文本末尾都会带一个'\n'换行符,可以使用L.rstrip('\n')去掉1234
readlines() Advantages: Reading the text content at one time is relatively fast. Disadvantages of readlines(): As the text increases, it will occupy more and more memory.
file=open('test.txt','r')try: for line in file: print line finalli: file.close()
Recommended tutorial: "
python tutorialThe above is the detailed content of What three methods does python provide for reading the contents of text files?. For more information, please follow other related articles on the PHP Chinese website!