python读取csv、JSON、XML、Avro文件,并在pyqt5设计页面显示csv、JSON、XML、Avro文件数据
时间: 2023-12-04 13:06:25 浏览: 139
读取csv文件:
```python
import csv
with open('file.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
```
显示csv文件数据:
```python
from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem
table = QTableWidget()
with open('file.csv', 'r') as file:
reader = csv.reader(file)
table.setRowCount(len(list(reader)))
table.setColumnCount(len(next(reader)))
file.seek(0)
for i, row in enumerate(reader):
for j, value in enumerate(row):
item = QTableWidgetItem(value)
table.setItem(i, j, item)
```
读取JSON文件:
```python
import json
with open('file.json', 'r') as file:
data = json.load(file)
print(data)
```
显示JSON文件数据:
```python
from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem
table = QTableWidget()
with open('file.json', 'r') as file:
data = json.load(file)
table.setRowCount(len(data))
table.setColumnCount(len(data[0]))
for i, row in enumerate(data):
for j, value in enumerate(row):
item = QTableWidgetItem(value)
table.setItem(i, j, item)
```
读取XML文件:
```python
import xml.etree.ElementTree as ET
tree = ET.parse('file.xml')
root = tree.getroot()
for child in root:
print(child.tag, child.attrib)
```
显示XML文件数据:
```python
from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem
table = QTableWidget()
tree = ET.parse('file.xml')
root = tree.getroot()
table.setRowCount(len(root))
table.setColumnCount(len(root[0]))
for i, child in enumerate(root):
for j, value in enumerate(child.attrib.values()):
item = QTableWidgetItem(value)
table.setItem(i, j, item)
```
读取Avro文件:
```python
import avro.schema
from avro.datafile import DataFileReader, DataFileWriter
from avro.io import DatumReader, DatumWriter
schema = avro.schema.parse(open("file.avsc", "rb").read())
with open("file.avro", "rb") as fo:
reader = DataFileReader(fo, DatumReader())
for user in reader:
print(user)
reader.close()
```
显示Avro文件数据:
```python
from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem
table = QTableWidget()
schema = avro.schema.parse(open("file.avsc", "rb").read())
with open("file.avro", "rb") as fo:
reader = DataFileReader(fo, DatumReader())
data = []
for user in reader:
data.append(list(user.values()))
reader.close()
table.setRowCount(len(data))
table.setColumnCount(len(data[0]))
for i, row in enumerate(data):
for j, value in enumerate(row):
item = QTableWidgetItem(str(value))
table.setItem(i, j, item)
```
阅读全文