使用python把字符串写入文件中,要求写入的在最前面。
时间: 2024-02-09 12:08:44
浏览: 294

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"` 加上原来的内容。
阅读全文
相关推荐

















