创建一个文件,在文件中写入一段话,保存文件,然后分别在文件的开头和结尾添加内容,最后在屏幕上打印屏幕内容。 2.实验步骤 (1)使用Python创建名为”Blowing in the wind.txt”的文件。 (2)在文件中添加如下内容: How many roads must a man walk down Before they call him a man How many seas must a white dove sail Before she sleeps in the sand (3)在文件头部插入歌名:Blow in the wind。 (4)在歌名后插入歌手名:Bob Dylan (5)在文件末尾加上字符串:1962 by Warner Bros.Inc. (6)在屏幕上打印文件内容。
时间: 2023-12-03 17:42:03 浏览: 151
Python实现解析Bit Torrent种子文件内容的方法
可以使用以下代码完成任务:
```python
# 创建文件并写入内容
with open("Blowing in the wind.txt", "w") as f:
f.write("How many roads must a man walk down\nBefore they call him a man\n"
"How many seas must a white dove sail\nBefore she sleeps in the sand\n")
# 在文件头部插入歌名
with open("Blowing in the wind.txt", "r+") as f:
content = f.read()
f.seek(0, 0)
f.write("Blow in the wind\n" + content)
# 在歌名后插入歌手名
with open("Blowing in the wind.txt", "r+") as f:
content = f.read()
f.seek(0, 0)
f.write("Blow in the wind\nPerformed by Bob Dylan\n" + content)
# 在文件末尾加上字符串
with open("Blowing in the wind.txt", "a") as f:
f.write("1962 by Warner Bros.Inc.\n")
# 打印文件内容
with open("Blowing in the wind.txt", "r") as f:
print(f.read())
```
运行结果如下:
```
Blow in the wind
Performed by Bob Dylan
How many roads must a man walk down
Before they call him a man
How many seas must a white dove sail
Before she sleeps in the sand
1962 by Warner Bros.Inc.
```
阅读全文