10-1 Python 学习笔记

1. 项目

在文本编辑器中新建一个文件,写几句话来总结一下你至此学到的 Python 知识,其中每一行都以“In Python you can”打头。

将这个文件命名为learning_python.txt,并将其存储到为完成本章练习而编写的程序所在的目录中。

编写一个程序,它读取这个文件,并将你所写的内容打印三次:

第一次打印时读取整个文件;

第二次打印时遍历文件对象;

第三次打印时将各行存储在一个列表中,再在 with 代码块外打印它们。

 

2. 代码

创建一个learning_Python.txt的文件,存储内容:

 

 编写learning_python.py代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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. 执行结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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

  

 

posted @   JRS077  阅读(208)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示