读取文件,并按原格式输出文件内容的三种方式

 1 filename = 'Car.py'
 2 
 3 #读取整个文件
 4 with open(filename) as file_object:
 5     lines = file_object.read()
 6     print(lines)
 7 
 8 
 9 #遍历文件对象
10 with open(filename) as file_object:
11     for line in file_object:
12         print(line.strip('\n'))
13 
14 #将各行存储在一个列表中,再在with代码块外打印它们
15 with open(filename) as file_object:
16     lines = file_object.readlines()
17 
18 for line in lines:
19     print(line.strip('\n'))

 

posted @ 2018-11-09 20:22  悦来风清  阅读(403)  评论(0编辑  收藏  举报