Python 文件读写:将字符串写入文件357


在 Python 中,您可以使用内置的 open() 函数打开一个文件并对其进行读写操作。要将字符串写入文件,您可以使用 open() 函数的 write() 方法。

以下是将字符串写入文件的步骤:1. 打开文件:
```python
file = open("", "w") # 以写入模式打开文件
```
2. 写入字符串:
```python
("Hello, world!") # 将字符串写入文件
```
3. 关闭文件:
```python
() # 关闭文件以保存更改
```

您还可以使用 with 语句来打开文件,它会自动关闭文件,从而简化资源管理:```python
with open("", "w") as file:
("Hello, world!")
```

附加模式('a')

如果您希望追加数据到现有文件而不是覆盖它,可以使用附加模式('a'):```python
with open("", "a") as file:
("New line of text")
```

二进制模式('wb')

如果您要写入二进制数据(例如图像或声音文件),请使用二进制模式('wb'):```python
with open("", "wb") as file:
(b"Binary data")
```

示例:创建一个带有 10 行随机数据的 CSV 文件```python
import random
with open("", "w") as file:
for i in range(10):
("{},{},{}".format((1, 10), (1, 10), (1, 10)))
```

这将创建一个名为 "" 的 CSV 文件,其中包含 10 行随机整数数据。

其他注意事项
确保写入模式('w' 或 'a')与您要执行的操作相匹配。
如果您要在写入之前清空文件,请使用 truncate() 方法:
```python
(0)
```
您可以在写入前使用 seek() 方法将文件指针移动到特定位置。

2024-10-15


上一篇:Python 数据挖掘实战:探索数据的宝藏

下一篇:Python 字符串中查找子字符串