代码之家  ›  专栏  ›  技术社区  ›  MarcoPolo11

将CSV文件转换为xlsx文件Python

  •  4
  • MarcoPolo11  · 技术社区  · 7 年前

    大家好,我正在寻找代码的解决方案,我尝试将CSV文件转换为XLSX文件,然后将我的所有数据缩减为一列,列之间用 ; . (见下图)

    您能帮我解决这两个代码中的一个,以便在转换时使数据表示等于csv文件吗??(见图)

    以下两个代码给出了相同的结果:(重要信息,我正在Jupyter笔记本上使用Python 3.6 env):


    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文件数据组织: Picture:This is my CSV file data organization

    这就是我将其转换为XLSX时得到的结果: Picture: And this is what I get when I convert it into an XLSX

    从注释编辑

    好吧,所以我用了“深空” program :

     import pandas as pd
    
     pd.read_csv('C:/Users/Pictures/LOGS.CSV')
       .to_excel('C:/Users/Pictures/excel.xlsx')
    

    我仍然得到这个: Image Program xlsx response

    好的解决方案: 转换非常好。但在我的例子中,第一列不知怎么被移动了。Data num字符串位于nothing下,第一列是其值。。。(见下图)

    CSV file

    xlsx converted file

     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)
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   Nate    3 年前

    您的文件有问题。重命名或 save them as .txt files first . 然后,如注释中所述,使用pandas(@DeepSpace)并指定分隔符(@Marichyasana)。

    鉴于

    A. 已重命名 文本文件(例如。 LOGS1.txt )分号分隔列的,例如:

    0;2;DT#1970-01-01-00:46:09;55;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0
    1;2;DT#1970-01-01-00:46:25;71;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0
    2;2;DT#1970-01-01-00:46:28;74;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0
    3;2;DT#1970-01-01-00:46:30;76;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0
    4;2;DT#1970-01-01-00:46:32;78;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0
    5;2;DT#1970-01-01-00:46:34;80;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0
    ...
    

    密码

    import pandas as pd
    
    
    filepath_in = "C:/Users/Pictures/LOGS1.txt"
    filepath_out = "C:/Users/Pictures/excel.xlsx"
    pd.read_csv(filepath_in, delimiter=";").to_excel(filepath_out, index=False)
    

    对第二个文件应用相同的过程( LOGS2.txt ).