10-1 Python 学习笔记:在文本编辑器中新建一个文件,写几句话来总结一下你至此学到的Python 知识,其中每一行都以“In Python you can”打头。将这个文件命名为learning_python.txt,并将其存储到为完成本章练习而编写的程序所在的目录中。编写一个程序,它读取这个文件,并将你所写的内容打印三次:第一次打印时读取整个文件;第二次打印时遍历文件对象;第三次打印时将各行存储在一个列表中,再在with 代码块外打印它们。
新建文件learning_python.txt并添加如下内容
In Python you can Handle file
In Python you can Automatic operation and maintenance
In Python you can make AI
编写python代码
filename='learning_python.txt'
with open(filename) as file_object:
contents = file_object.read()
print(contents.rstrip()) print('') with open(filename) as file_object:
for line in file_object:
print(line.rstrip()) print('') with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
执行结果
In Python you can Handle file
In Python you can Automatic operation and maintenance
In Python you can make AI In Python you can Handle file
In Python you can Automatic operation and maintenance
In Python you can make AI In Python you can Handle file
In Python you can Automatic operation and maintenance
In Python you can make AI
总结:
with 在不需要访问文件后将其关闭
open()返回一个表示文件对象,python将这个文件对象储存到 file_object变量里
read()方法读取文件对象的全部内容,并将其作为一个长长的字符串存储在变量contents中
readlines()方法逐行读取文件对象