python 将字符串写入txt
时间: 2023-10-06 22:05:28 浏览: 289
文件的方法是什么?
将一个字符串写入txt文件的python代码如下:
```python
# 打开一个txt文件
file = open('example.txt', 'w')
# 要写入的字符串
string = "Hello, world!"
# 将字符串写入txt文件
file.write(string)
# 关闭txt文件
file.close()
```
在上面的代码中,首先使用open函数打开一个txt文件并指定"w"模式,这表示我们将创建一个新的文件并写入数据。接下来,我们将要写入的字符串分配给变量string。最后,我们使用write方法将字符串写入文件,并使用close方法关闭文件。
相关问题
python把字符串写入txt文件
可以使用Python的文件操作功能将字符串写入txt文件。以下是一个例子:
```python
# 打开文件,如果文件不存在则创建新文件
file = open("example.txt", "w")
# 将字符串写入文件
file.write("Hello, World!")
# 关闭文件
file.close()
```
在这个例子中,我们使用`open()`函数打开一个名为`example.txt`的文件。第二个参数`"w"`表示我们要写入文件,如果文件不存在则创建新文件。然后,我们使用`write()`方法将字符串`"Hello, World!"`写入文件。最后,我们使用`close()`方法关闭文件。
python 如何将字符串写入txt文件
可以使用 Python 内置的 `open()` 函数来打开一个文件,然后使用 `write()` 函数将字符串写入文件中。具体步骤如下:
1. 使用 `open()` 函数打开一个文件,可以指定文件名和打开方式(读、写、追加等)。
2. 使用 `write()` 函数将字符串写入文件中。
3. 使用 `close()` 函数关闭文件。
示例代码如下:
```python
# 打开文件,以写入模式打开
file = open("example.txt", "w")
# 写入字符串
file.write("Hello, world!")
# 关闭文件
file.close()
```
执行完上述代码后,会在当前目录下创建一个名为 `example.txt` 的文件,并将字符串 `"Hello, world!"` 写入该文件中。
阅读全文
相关推荐













