Python-xlsx文件与csv文件相互转换
欢迎关注公众号:Python爬虫数据分析挖掘,回复【开源源码】免费获取更多开源项目源码
公众号每日更新python知识和【免费】工具
在2个文件之间转换,需要注意一个文件的字符转码问题。
xlsx文件转csv文件
-
使用xlrd和csv模块来处理Excel文件和csv文件
import xlrd
import csv
def xlsx_to_csv():
workbook = xlrd.open_workbook('1.xlsx')
table = workbook.sheet_by_index(0)
with codecs.open('1.csv', 'w', encoding='utf-8') as f:
write = csv.writer(f)
for row_num in range(table.nrows):
row_value = table.row_values(row_num)
write.writerow(row_value)
if __name__ == '__main__':
xlsx_to_csv()
-
使用第三方库pandas将xlsx文件转csv文件
import pandas as pd
def xlsx_to_csv_pd():
data_xls = pd.read_excel('1.xlsx', index_col=0)
data_xls.to_csv('1.csv', encoding='utf-8')
if __name__ == '__main__':
xlsx_to_csv_pd()
csv文件转换成xlsx文件
-
使用xlwt和csv模块来处理Excel文件和csv文件
import csv
import xlwt
def csv_to_xlsx():
with open('1.csv', 'r', encoding='utf-8') as f:
read = csv.reader(f)
workbook = xlwt.Workbook()
sheet = workbook.add_sheet('data') # 创建一个sheet表格
l = 0
for line in read:
print(line)
r = 0
for i in line:
print(i)
sheet.write(l, r, i) # 一个一个将单元格数据写入
r = r + 1
l = l + 1
workbook.save('1.xlsx') # 保存Excel
if __name__ == '__main__':
csv_to_xlsx()
-
使用pandas将csv文件转成xlsx文件
import pandas as pd
def csv_to_xlsx_pd():
csv = pd.read_csv('1.csv', encoding='utf-8')
csv.to_excel('1.xlsx', sheet_name='data')
if __name__ == '__main__':
csv_to_xlsx_pd()
耐得住寂寞,才能登得顶
Gitee码云:https://gitee.com/lyc96/projects