csv中有int类型和str类型怎么转换
时间: 2024-05-10 18:16:26 浏览: 20
如果你需要将 CSV 文件中的某些列从字符串类型转换为整数类型,可以使用 Python 的 csv 模块和 int() 函数。
假设你的 CSV 文件长这样:
```
name,age,city
Alice,25,New York
Bob,30,San Francisco
Charlie,40,Los Angeles
```
你可以按照以下步骤将 age 列的值从字符串类型转换为整数类型:
```python
import csv
with open('data.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
age = int(row['age'])
print(type(age), age)
```
这里使用了 csv.DictReader() 函数读取 CSV 文件的内容,并使用 int() 函数将 age 列的值从字符串类型转换为整数类型。
输出结果是:
```
<class 'int'> 25
<class 'int'> 30
<class 'int'> 40
```
如果你需要将整数类型的值转换为字符串类型,可以使用 str() 函数。例如:
```python
import csv
with open('data.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
age = int(row['age'])
age_str = str(age)
print(type(age_str), age_str)
```
输出结果是:
```
<class 'str'> 25
<class 'str'> 30
<class 'str'> 40
```
这里使用了 str() 函数将 age 列的整数值转换为字符串类型。