【练习】读写文件
项目简介
读写文件
知识模块
- Python 编程语言
知识点
- 文件操作
受众
- 初级测试开发工程师
- 初级Python开发工程师
作业要求
编写一个Python程序,将一些文本内容写入到文件中,并且能够从文件中读取内容并显示出来。
解题思路
- 使用文件的属性和方法进行操作
完整代码
file_name = "my_file.txt"
content = "Hello, this is a text file."
with open(file_name, "w") as file:
file.write(content)
print(f"内容已写入文件:{file_name}")
# 读取文件
with open(file_name, "r") as file:
file_content = file.read()
print(f"文件内容:\n{file_content}")
代码讲解
-
content = "Hello, this is a text file."
定义一个变量 content,表示要写入到文件的文本内容。 -
with open(file_name, "w") as file
: - 使用open()
函数以写入模式"w"
打开文件,并将文件对象赋值给变量file
。with
语句保证在块结束后文件会自动关闭。 -
file.write(content)
使用文件对象的write()
方法写入文本内容到文件。 -
with open(file_name, "r") as file
: 使用open()
函数以读取模式"r"
打开同一个文件,同样使用with
语句以自动关闭文件。 -
file_content = file.read()
使用文件对象的read()
方法读取文件内容,将内容赋值给变量file_content
。