欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python读写操作csv和excle文件代码实例

时间:2021-03-17 09:39:36|栏目:Python代码|点击:

1、python读写csv文件

import csv

#读取csv文件内容方法1
csv_file = csv.reader(open('testdata.csv','r'))
next(csv_file, None)  #skip the headers
for user in csv_file:
  print(user)

#读取csv文件内容方法2
with open('testdata.csv', 'r') as csv_file:
  reader = csv.reader(csv_file)
  next(csv_file, None)
  for user in reader:
    print(user)

#从字典写入csv文件
dic = {'fengju':25, 'wuxia':26}
csv_file = open('testdata1.csv', 'w', newline='')
writer = csv.writer(csv_file)
for key in dic:
  writer.writerow([key, dic[key]])
csv_file.close()  #close CSV file

csv_file1 = csv.reader(open('testdata1.csv','r'))
for user in csv_file1:
  print(user)

2、python读写excle文件

 需要先用python pip命令安装xlrd , xlwt库~

import xlrd, xlwt  #xlwt只能写入xls文件

#读取xlsx文件内容
rows = []  #create an empty list to store rows
book = xlrd.open_workbook('testdata.xlsx') #open the Excel spreadsheet as workbook
sheet = book.sheet_by_index(0)  #get the first sheet
for user in range(1, sheet.nrows): #iterate 1 to maxrows
  rows.append(list(sheet.row_values(user, 0, sheet.ncols))) #iterate through the sheet and get data from rows in list
print(rows)

#写入xls文件
rows1 = [['Name', 'Age'],['fengju', '26'],['wuxia', '25']]
book1 = xlwt.Workbook()  #create new book1 excle
sheet1 = book1.add_sheet('user')  #create new sheet
for i in range(0, 3):  
  for j in range(0, len(rows1[i])):
    sheet1.write(i, j, rows1[i][j])
book1.save('testdata1.xls')  #sava as testdata1.xls

上一篇:python爬虫爬取笔趣网小说网站过程图解

栏    目:Python代码

下一篇:CentOS 7 安装python3.7.1的方法及注意事项

本文标题:Python读写操作csv和excle文件代码实例

本文地址:http://www.codeinn.net/misctech/82256.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有