Python流式读取文件|Python按行读取文件

如以只读方式使用UTF-8编码方案读取tree.txt,并在读完之后关闭文件。
方法一:循环读取所有行

with open('tree.txt', 'r', encoding='utf-8') as f:
    for line in f:
        print(line)
    f.close()

方法二:先读取一行,再接着循环读取下面的所有行

with open('tree.txt', 'r', encoding='utf-8') as f:
	line = f.readline()
	print(line)
	while(line):
		line = f.readline()
		print(line)
	f.close()

你可能感兴趣的:(Python)