首先写作一篇自我介绍的英文文章,然后编写程序,先追加一行姓名、学号到原有文件,然后读取文档中的全部内容,并打印输出。效果如图所示。 注意:文件打开模式的选择,文件及时关闭,可以按行读取文件内容。
时间: 2023-12-05 11:06:14 浏览: 121
python之文件读取一行一行的方法
Here is my self-introduction:
My name is Tom, and I am a junior student majoring in computer science. I have a strong passion for programming and enjoy exploring new technologies. In my spare time, I like to participate in programming contests and contribute to open-source projects. I believe that continuous learning is the key to success in this rapidly changing field, and I am always eager to learn more.
And here is the program that appends my name and student ID to the original file and prints out the entire content:
```python
# Open the file in append mode and write my name and student ID
with open("self_introduction.txt", mode="a") as f:
f.write("\nName: Tom\nStudent ID: 123456")
# Read and print the entire content of the file
with open("self_introduction.txt", mode="r") as f:
content = f.readlines()
for line in content:
print(line.strip())
```
The output will be:
```
My name is Tom, and I am a junior student majoring in computer science. I have a strong passion for programming and enjoy exploring new technologies. In my spare time, I like to participate in programming contests and contribute to open-source projects. I believe that continuous learning is the key to success in this rapidly changing field, and I am always eager to learn more.
Name: Tom
Student ID: 123456
```
阅读全文