python如何写入写出数据类型
- 编程技术
- 2025-02-05 16:37:12
- 1
![python如何写入写出数据类型](http://xinin56.com/imgs/102.jpg)
在Python中,可以使用多种方式来写入和读取不同类型的数据。以下是一些常见的数据类型及其写入和读取的方法: 1. 文本数据(str)写入:使用文件操作中的写入方法,如...
在Python中,可以使用多种方式来写入和读取不同类型的数据。以下是一些常见的数据类型及其写入和读取的方法:
1. 文本数据(str)
写入:使用文件操作中的写入方法,如 `write()` 或 `writelines()`。
```python
with open('example.txt', 'w') as file:
file.write('Hello, World!')
```
读取:使用 `read()` 或 `readlines()`。
```python
with open('example.txt', 'r') as file:
content = file.read()
print(content)
```
2. 数字(int, float)
写入:与文本类似,但要注意转换为字符串。
```python
with open('example.txt', 'w') as file:
file.write(str(123))
```
读取:同样转换为字符串,然后转换回原始类型。
```python
with open('example.txt', 'r') as file:
content = file.read()
number = int(content)
print(number)
```
3. 列表(list)
写入:转换为字符串或使用JSON格式。
```python
import json
data = [1, 2, 3, 4, 5]
with open('example.txt', 'w') as file:
file.write(str(data))
或者使用JSON格式
json.dump(data, file)
```
读取:读取字符串后,转换回列表。
```python
with open('example.txt', 'r') as file:
content = file.read()
如果使用JSON格式
data = json.load(file)
如果使用字符串
data = eval(content)
print(data)
```
4. 字典(dict)
写入:与列表类似,使用JSON格式。
```python
data = {'key': 'value'
本文链接:http://xinin56.com/bian/475578.html
上一篇:在安通信一级建造师证多少钱一个月