使用Python怎么读写csv和excle文件

发布时间:2021-04-30 15:55:04 作者:Leah
来源:亿速云 阅读:175

使用Python怎么读写csv和excle文件?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

python可以做什么

Python是一种编程语言,内置了许多有效的工具,Python几乎无所不能,该语言通俗易懂、容易入门、功能强大,在许多领域中都有广泛的应用,例如最热门的大数据分析,人工智能,Web开发等。

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怎么读写csv和excle文件问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

推荐阅读:
  1. python读写csv文件的实战
  2. python怎样读写csv文件

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:使用python怎么通过邮件控制远程电脑

下一篇:怎么在Python中使用semaphore evevt实现生产者消费者模型

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》