python练习将 string, list, tuple, dict类型的数据写入到文件中
时间: 2023-12-09 14:05:35 浏览: 257
Python将列表数据写入文件(txt, csv,excel)
以下是将不同类型的数据写入文件的示例代码:
1. 写入字符串到文件
```python
text = "Hello, world!"
with open("file.txt", "w") as f:
f.write(text)
```
2. 写入列表到文件
```python
my_list = [1, 2, 3, 4, 5]
with open("file.txt", "w") as f:
for item in my_list:
f.write(str(item) + "\n")
```
3. 写入元组到文件
```python
my_tuple = (1, 2, 3, 4, 5)
with open("file.txt", "w") as f:
for item in my_tuple:
f.write(str(item) + "\n")
```
4. 写入字典到文件
```python
my_dict = {"name": "John", "age": 30, "city": "New York"}
with open("file.txt", "w") as f:
for key, value in my_dict.items():
f.write(key + ":" + str(value) + "\n")
```
注意:在写入数据时,要确保将所有数据转换为字符串类型,因为文件只能保存字符串类型的数据。
阅读全文