利用相关库,用Python实现CSV、Excel、Word文件的创建和读写操作
时间: 2024-05-14 11:13:39 浏览: 120
可以使用Python自带的csv、xlrd、xlwt、openpyxl、docx等库实现CSV、Excel、Word文件的创建和读写操作。例如,使用csv库可以通过以下代码将数据写入CSV文件中:
```python
import csv
data = [['name', 'age', 'gender'], ['Tom', 18, 'male'], ['Lily', 20, 'female']]
filename = 'data.csv'
with open(filename, 'w', newline='') as f:
writer = csv.writer(f)
for row in data:
writer.writerow(row)
```
使用xlwt库可以通过以下代码将数据写入Excel文件中:
```python
import xlwt
data = [['name', 'age', 'gender'], ['Tom', 18, 'male'], ['Lily', 20, 'female']]
filename = 'data.xls'
workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook.add_sheet('Sheet1')
for i, row in enumerate(data):
for j, col in enumerate(row):
worksheet.write(i, j, col)
workbook.save(filename)
```
使用openpyxl库可以通过以下代码将数据写入Excel文件中:
```python
import openpyxl
data = [['name', 'age', 'gender'], ['Tom', 18, 'male'], ['Lily', 20, 'female']]
filename = 'data.xlsx'
workbook = openpyxl.Workbook()
worksheet = workbook.active
for row in data:
worksheet.append(row)
workbook.save(filename)
```
使用docx库可以通过以下代码将数据写入Word文件中:
```python
import docx
data = [['name', 'age', 'gender'], ['Tom', 18, 'male'], ['Lily', 20, 'female']]
filename = 'data.docx'
document = docx.Document()
for row in data:
table = document.add_table(rows=1, cols=len(row))
hdr_cells = table.rows[0].cells
for i, col in enumerate(row):
hdr_cells[i].text = col
document.save(filename)
```
阅读全文