利用python完成(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 12:47:32 浏览: 84
WLKATA MIROBOT Python SDK使用手册1
以下是实现上述要求的Python代码:
```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\nHow 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')
f.write(content)
# 在歌名后插入歌手名
with open('Blowing in the wind.txt', 'r+') as f:
content = f.read()
f.seek(0, 0) # 移动文件指针到文件头部
f.write('Blow in the wind\nby Bob Dylan\n')
f.write(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:
content = f.read()
print(content)
```
运行以上代码后,会在当前目录下创建一个名为“Blowing in the wind.txt”的文件,并按照要求写入内容。最后一行会在屏幕上打印文件的完整内容。
阅读全文