python怎么保存文件
时间: 2024-01-10 15:37:30 浏览: 167
你可以使用 Python 的内置函数 `open()` 来保存文件。下面是一个简单的示例代码,演示如何将文本保存到文件中:
```python
def save_file(filename, content):
with open(filename, 'w') as file:
file.write(content)
print(f"文件 '{filename}' 保存成功!")
filename = 'example.txt'
content = '这是要保存的内容。'
save_file(filename, content)
```
在上面的代码中,`save_file()` 函数接受一个文件名和要保存的内容作为参数。它使用 `open()` 函数以写入模式打开文件,并使用 `write()` 方法将内容写入文件中。最后,使用 `with` 语句块来确保文件在使用后正确关闭。
你可以根据需要修改文件名和内容,运行代码后,将会在当前目录下生成一个名为 `example.txt` 的文件,其中包含指定的内容。
注意:如果文件不存在,`open()` 函数会自动创建一个新文件。如果文件已存在,它将被覆盖。如果你想要追加内容而不是覆盖原文件,可以将打开模式改为 `'a'`。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)