- Python数据整理
- (美)提尔塔吉奥蒂·萨卡 (印)舒布哈迪普·罗伊乔杜里
- 208字
- 2025-02-14 17:47:31
练习25:写入文件
我们将通过写入文件这个练习来结束有关文件操作的主题。我们将对一个文件写入几行字符并读取该文件。
1.使用文件描述符对象中的write函数:

2.使用以下命令读取文件:

输出如下:

3.通过以下命令使用print函数写入文件:

4.使用以下命令读取文件:

输出如下:

说明
在第二个例子中,我们没有在要写入的字符串末尾添加换行符\n。print函数会自动添加。
通过本练习,我们即将结束该主题。与前面的主题一样,我们设计了一个活动,让你练习获得的新技能。