一、CSV文件
1 读csv文件
1.1 以数组方式读文件
def listReader():
with open("user.csv", encoding="UTF-8") as csvFile:
csvData = csv.reader(csvFile)
print(list(csvData))
for data in csvData:
print("%s = " % csvData.line_num, data)
1.2 以字典方式读文件
def dictReader():
with open("user.csv", encoding="UTF-8") as csvFile:
csvData = csv.DictReader(csvFile)
for data in csvData:
print(row['name'],row['age'])
2 写csv文件
2.1 写入行
方式一:直接写入
def rowWrite01():
with open('test.csv', 'w', newline='') as csvFile:
file = csv.writer(csvFile)
file.writerow(['Name', 'Age', 'City'])
file.writerow(['luck', '18', 'BeiJing'])
file.writerow(['Jucy', '20', 'ShangHai'])
方式二:使用delimiter分隔符
def rowWrite02():
with open('test.csv', 'w', newline='') as csvFile:
file = csv.writer(csvFile, delimiter='\t')
file.writerow(['Name', 'Age', 'City'])
file.writerow(['luck', '18', 'BeiJing'])
file.writerow(['Jucy', '20', 'Shan,gHai'])
2.2 使用字典写入
方式一:直接写入
def dictRowWrite():
with open('test.csv', 'w', newline='') as csvFile:
fields = ['Name', 'Age', 'City']
file = csv.DictWriter(csvFile, fieldnames=fields)
file.writeheader()
file.writerow({'Name': 'luck', 'Age': '19', 'City': 'BeiJing'})
file.writerow({'Name': 'Jucy', 'Age': '21', 'City': 'ShangHai'})
方式二:循环写入
def dictWrite():
dictList = [{'Name': 'luck', 'Age': '19', 'City': 'BeiJing'},
{'Name': 'Jucy', 'Age': '21', 'City': 'ShangHai'}]
with open('test.csv', 'w', newline='') as csvFile:
fields = ['Name', 'Age', 'City']
file = csv.DictWriter(csvFile, fieldnames=fields)
file.writeheader()
for row in dictList:
file.writerow(row)
二、Excel文件
1 下载读Excel所需要的库文件xlrd2
pip install xlrd2
2 读Excel文件
import xlrd2
def excelReader(sheet):
for row in range(1, sheet.nrows):
data = {'id': '', 'name': '', 'age': '',
'sex': '', 'deleted': '', 'version': ''}
data['id'] = sheet.cell_value(row, 0)
data['name'] = sheet.cell_value(row, 1)
data['age'] = sheet.cell_value(row, 2)
data['sex'] = sheet.cell_value(row, 3)
data['deleted'] = sheet.cell_value(row, 4)
data['version'] = sheet.cell_value(row, 5)
if __name__ == '__main__':
workBook = xlrd2.open_workbook('user.xlsx')
sheetName = workBook.sheets()[0]
excelReader(sheetName)
import xlrd2
wb = xlrd2.open_workbook("Excel的路径")
sheet_num = wb.nsheets
sheet_names = wb.sheet_names()
sheet = wb.sheet_by_index(0)
rows = sheet.nrows
columns = sheet.ncols
row_data = sheet.row_values(0)
col_data = sheet.col_values(1)
row_col_data = sheet.cell_value(row, col)
one_data = sheet.cell(row_index, col_index)
cell_value = one_data.value
cell_type = one_data.ctype
0 -- 空(empty)
1 -- 字符串(string)
2 -- 数字(number)
3 -- date(日期)
4 -- boolean(布尔值)
5 -- error(错误)