python读取csv文件将万转换成纯数字
时间: 2023-07-15 07:14:05 浏览: 80
可以使用 Python 自带的 csv 模块和 re 模块来读取 csv 文件并将万转换为纯数字。以下是一个示例代码:
```python
import csv
import re
with open('data.csv', 'r', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
# 将万转换为纯数字
pattern = re.compile(r'\d+\.?\d*万')
for i in range(len(row)):
if pattern.search(row[i]):
res = round(float(pattern.search(row[i]).group(0)[:-1]) * 10000)
row[i] = str(res)
print(row)
```
其中,`data.csv` 是你要读取的 csv 文件名,可以根据需要修改。这段代码会将 csv 文件中的每一行都转换一遍,将其中的所有万转换为对应的纯数字,并输出转换后的结果。
相关问题
python 读取csv文件转成字符串_Python将csv文件转换为json文件
要将 CSV 文件读取并转换为字符串,可以使用 Python 的内置 csv 模块。下面是一个示例代码:
```python
import csv
with open('file.csv', newline='') as csvfile:
csv_reader = csv.reader(csvfile)
for row in csv_reader:
print(','.join(row)) # 将每行转换为字符串并打印出来
```
这将打开名为 file.csv 的 CSV 文件,并将每行转换为字符串并打印出来。
要将 CSV 文件转换为 JSON 文件,可以使用 Python 的内置 json 模块。下面是一个示例代码:
```python
import csv
import json
csvfile = open('file.csv', 'r')
jsonfile = open('file.json', 'w')
fieldnames = ("Name", "Age", "Gender")
reader = csv.DictReader(csvfile, fieldnames)
for row in reader:
json.dump(row, jsonfile)
jsonfile.write('\n')
```
这将打开名为 file.csv 的 CSV 文件,并使用列标题作为键将每行转换为 JSON 对象,并将这些 JSON 对象写入名为 file.json 的文件中。
python读取csv文件转换成int类型
可以使用Python内置的csv模块来读取csv文件,并使用int()函数将读取的字符串转换为整数类型。
以下是一个示例代码:
```python
import csv
with open('example.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
# 将第一列和第二列转换为整数类型
col1 = int(row[0])
col2 = int(row[1])
print(col1, col2)
```
在这个示例代码中,我们打开一个名为example.csv的文件,使用csv.reader()函数将其读取为一个可迭代的对象。然后,我们遍历每一行并使用int()函数将第一列和第二列转换为整数类型,最后将它们打印出来。