2.编写程序将CSV格式文件与json文件格式互相转换,用python写
时间: 2023-11-22 08:54:37 浏览: 42
下面是将CSV文件转换成JSON文件的Python代码:
```python
import csv
import json
csvFilePath = 'example.csv'
jsonFilePath = 'example.json'
# Read CSV file and convert it into a dictionary
data = {}
with open(csvFilePath) as csvFile:
csvReader = csv.DictReader(csvFile)
for rows in csvReader:
id = rows['ID']
data[id] = rows
# Write dictionary to JSON file
with open(jsonFilePath, 'w') as jsonFile:
jsonFile.write(json.dumps(data, indent=4))
```
下面是将JSON文件转换成CSV文件的Python代码:
```python
import csv
import json
jsonFilePath = 'example.json'
csvFilePath = 'example.csv'
# Read JSON file and convert it into a dictionary
with open(jsonFilePath) as jsonFile:
data = json.load(jsonFile)
# Extract column headers from the dictionary
fields = list(data.values())[0].keys()
# Write dictionary to CSV file
with open(csvFilePath, 'w') as csvFile:
writer = csv.DictWriter(csvFile, fieldnames=fields)
writer.writeheader()
writer.writerows(data.values())
```