用python把 string, list, tuple, dict类型的数据写入到文件里
时间: 2023-12-04 08:05:50 浏览: 95
可以使用Python内置的文件操作函数来写入不同类型的数据到文件中。
1. 写入字符串类型的数据
```python
data = "Hello World\nWelcome to Python\n"
with open("data.txt", "w") as f:
f.write(data)
```
2. 写入列表类型的数据
```python
data = ["apple", "banana", "orange"]
with open("data.txt", "w") as f:
for item in data:
f.write("%s\n" % item)
```
3. 写入元组类型的数据
```python
data = ("apple", "banana", "orange")
with open("data.txt", "w") as f:
for item in data:
f.write("%s\n" % item)
```
4. 写入字典类型的数据
```python
data = {"apple": 2, "banana": 3, "orange": 4}
with open("data.txt", "w") as f:
for key, value in data.items():
f.write("%s:%s\n" % (key, value))
```
在这些示例中,我们使用了Python的with语句来打开文件,并将数据写入文件。在with块结束时,文件会自动关闭。
阅读全文
相关推荐

















