写入文件 案例
时间: 2023-09-13 10:05:11 浏览: 44
好的,以下是一个简单的写入文件的案例:
```python
# 打开文件,以写入模式写入内容
with open('test.txt', 'w') as file:
file.write('Hello World!\n')
file.write('This is a test file.\n')
file.write('Goodbye!\n')
# 打开文件,以读取模式读取内容并打印
with open('test.txt', 'r') as file:
content = file.read()
print(content)
```
上述代码中,我们使用 `open()` 函数打开一个名为 `test.txt` 的文件,并使用 `'w'` 标志打开文件以进行写入。然后,我们使用 `write()` 函数写入三行文本。每行文本都以换行符 `\n` 结尾,以便在文件中创建新行。
接下来,我们再次使用 `open()` 函数打开 `test.txt` 文件,但这次使用 `'r'` 标志以读取文件。我们使用 `read()` 函数读取文件的内容,并将其存储在 `content` 变量中。最后,我们打印 `content` 变量的值,以显示文件中的内容。
运行上述代码后,将在当前工作目录中创建一个名为 `test.txt` 的文件,并将以下内容写入该文件:
```
Hello World!
This is a test file.
Goodbye!
```
然后,程序再次打开 `test.txt` 文件,并将其内容读取到 `content` 变量中。最后,程序将 `content` 变量的值打印到控制台中,显示文件中的内容。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)