10-1 Python 学习笔记
1. 项目
在文本编辑器中新建一个文件,写几句话来总结一下你至此学到的 Python 知识,其中每一行都以“In Python you can”打头。
将这个文件命名为learning_python.txt,并将其存储到为完成本章练习而编写的程序所在的目录中。
编写一个程序,它读取这个文件,并将你所写的内容打印三次:
第一次打印时读取整个文件;
第二次打印时遍历文件对象;
第三次打印时将各行存储在一个列表中,再在 with 代码块外打印它们。
2. 代码
创建一个learning_Python.txt的文件,存储内容:
编写learning_python.py代码
filename = 'learning_python.txt' print("************************1st*************************") with open(filename) as file_object: contents = file_object.read() print(contents.rstrip()) print("************************2nd*************************") with open(filename) as file_object: for line in file_object: print(line.rstrip()) print("************************3rd*************************") with open(filename) as file_object: lines = file_object.readlines() for line in lines: print(line.rstrip())
3. 执行结果
D:\python编程:从入门到实践\venv\Scripts\python.exe "D:/python编程:从入门到实践/第10章 文件和异常/learning_python.py" ************************1st************************* In Python you can learn string In Python you can learn tuple In Python you can learn sequence In Python you can learn dictionary ************************2nd************************* In Python you can learn string In Python you can learn tuple In Python you can learn sequence In Python you can learn dictionary ************************3rd************************* In Python you can learn string In Python you can learn tuple In Python you can learn sequence In Python you can learn dictionary Process finished with exit code 0