创建一个文件Blowing in the wind.txt,在文件头部插入歌名“Blowin'in the wind",在歌名后插入歌手名”Bob Dylan",在文件末尾加上字符串“1962 by Warner Bros. Inc.",在屏幕上输出文件内容
时间: 2023-12-14 14:38:03 浏览: 121
好的,以下是代码实现:
```python
# 打开文件,如果不存在则新建
with open('Blowing in the wind.txt', 'w+') as file:
# 在文件头部插入歌名
file.write('Blowin\' in the wind\n')
# 在歌名后插入歌手名
file.write('Bob Dylan\n')
# 在文件末尾加上字符串
file.write('1962 by Warner Bros. Inc.')
# 打开文件,并读取内容
with open('Blowing in the wind.txt', 'r') as file:
content = file.read()
# 在屏幕上输出文件内容
print(content)
```
输出结果为:
```
Blowin' in the wind
Bob Dylan
1962 by Warner Bros. Inc.
```
相关问题
使用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)在屏幕上打印文件内容。
以下是实现以上要求的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")
# 在文件头部插入歌名
with open("Blowing in the wind.txt", "r+") as f:
content = f.read()
f.seek(0, 0)
f.write("Blowin' in the wind\n" + content)
# 在歌名后插入歌手名
with open("Blowing in the wind.txt", "r+") as f:
content = f.read()
f.seek(0, 0)
f.write("Blowin' in the wind\nby Bob Dylan\n" + content[len("Blowin' in the wind\n"):])
# 在文件末尾加上字符串
with open("Blowing in the wind.txt", "a") as f:
f.write("\n1962 by Warner Bros.Inc.")
# 打印文件内容
with open("Blowing in the wind.txt", "r") as f:
print(f.read())
```
输出:
```
Blowin' in the wind
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.
```
利用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)在屏幕上打印文件内容。
以下是实现上述要求的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”的文件,并按照要求写入内容。最后一行会在屏幕上打印文件的完整内容。
阅读全文