python把字符串写入文件
时间: 2023-03-30 17:04:33 浏览: 289
可以使用Python的文件操作函数将字符串写入文件。例如,可以使用open()函数打开一个文件,然后使用write()函数将字符串写入文件中。示例代码如下:
```
with open('file.txt', 'w') as f:
f.write('Hello, world!')
```
这将在当前目录下创建一个名为file.txt的文件,并将字符串'Hello, world!'写入该文件中。
相关问题
使用python把字符串写入文件中,要求写入的在最前面。
可以使用Python中的文件操作函数 `write()` 和 `seek()` 来实现将字符串写入文件中并且在最前面。具体实现步骤如下:
1. 打开文件,使用 `open()` 函数来打开一个文件,并且使用参数 `"r+"` 表示读写模式。
```python
file = open("file.txt", "r+")
```
2. 读取文件内容,使用 `read()` 函数读取文件的所有内容,并且使用 `seek()` 函数将文件指针移到文件的开头。
```python
content = file.read()
file.seek(0)
```
3. 将字符串写入文件,使用 `write()` 函数将要写入的字符串写入文件中,并且将原来的内容追加在后面。
```python
file.write("hello, world!\n" + content)
```
4. 关闭文件,使用 `close()` 函数关闭文件。
```python
file.close()
```
完整代码如下:
```python
file = open("file.txt", "r+")
content = file.read()
file.seek(0)
file.write("hello, world!\n" + content)
file.close()
```
执行完毕后,文件内容会变成 `"hello, world!\n"` 加上原来的内容。
python把字符串写入txt文件
可以使用Python的文件操作功能将字符串写入txt文件。以下是一个例子:
```python
# 打开文件,如果文件不存在则创建新文件
file = open("example.txt", "w")
# 将字符串写入文件
file.write("Hello, World!")
# 关闭文件
file.close()
```
在这个例子中,我们使用`open()`函数打开一个名为`example.txt`的文件。第二个参数`"w"`表示我们要写入文件,如果文件不存在则创建新文件。然后,我们使用`write()`方法将字符串`"Hello, World!"`写入文件。最后,我们使用`close()`方法关闭文件。
相关推荐
![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)