大家好,我正在寻找我的代码的解决方案,我试图将CSV文件转换为XLSX文件,我的所有数据都被压缩成一个由;分隔的列。(见下图)
请你帮我解决这两个代码中的一个,以便在转换为csv文件时使数据表示形式化??(见图片)
以下两个代码给出了相同的结果:(重要的是,我正在Jupyter笔记本上使用Python 3.6env):import os
import glob
import csv
from xlsxwriter.workbook import Workbook
for csvfile in glob.glob(os.path.join('.', 'LOGS.CSV')):
workbook = Workbook(csvfile[:-4] + '.xlsx')
worksheet = workbook.add_worksheet()
with open(csvfile, 'r') as f:
reader = csv.reader((line.replace('\0','-') for line in f))
for r, row in enumerate (reader):
for c, col in enumerate(row):
worksheet.write(r, c, col)
workbook.close()import os
import csv
import sys
from openpyxl import Workbook
data_initial = open("new.csv", "r")
sys.getdefaultencoding()
workbook = Workbook()
worksheet = workbook.worksheets[0]
with data_initial as f:
data = csv.reader((line.replace('\0','') for line in data_initial), delimiter=",")
for r, row in enumerate(data):
for c, col in enumerate(row):
for idx, val in enumerate(col.split('/')):
cell = worksheet.cell(row=r+1, column=c+1)
cell.value = val
workbook.save('output.xlsx')
这是我的CSV文件数据组织:
这就是我把它转换成XLSX时得到的结果:
从评论编辑
好吧,我用了@DeepSpace的program:import pandas as pd
pd.read_csv('C:/Users/Pictures/LOGS.CSV')
.to_excel('C:/Users/Pictures/excel.xlsx')
我仍然明白:
好的解决方案:
转换很好。但在我的例子中,第一列不知怎么被移动了。Data num字符串不在任何值下,第一列是它的值。。。(见下图)
import pandas as pd
filepath_in = "C:/Users/Pictures/LOGS.csv"
filepath_out = "C:/Users/Pictures/excel.xlsx"
pd.read_csv(filepath_in, delimiter=";").to_excel(filepath_out)