将 CSV 文件转换为 xlsx 文件 Python

2024-02-01

大家好,我正在寻找代码的解决方案,我尝试将 CSV 文件转换为 XLSX 文件,并且所有数据都缩减为一列,并用;。 (见下面的图片)

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

以下两个代码给出相同的结果:(重要的是,我在 Jupyter Notebook 上使用 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')

This is my CSV file data organization: Picture:This is my CSV file data organization

And this is what I get when I convert it into an XLSX: Picture: And this is what I get when I convert it into an XLSX

根据评论编辑

好的,所以我用了@DeepSpace 的program https://stackoverflow.com/questions/48747988/convert-csv-file-to-xlsx-file-python#comment84496089_48747988:

 import pandas as pd

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

and I am still getting this: Image Program xlsx response

好的解决方案:转换很棒。但就我而言,第一列以某种方式移动了。数据数字字符串什么都没有,第一列是它的值......(见下图)

 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)

您的文件有问题。重命名或将它们另存为.txt文件优先 https://support.office.com/en-us/article/import-or-export-text-txt-or-csv-files-5250ac4c-663c-47ce-937b-339e391393ba。然后如评论中所述,使用 pandas (@DeepSpace) 并指定分隔符 (@Marichyasana)。

Given

A renamed文本文件(例如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
...

Code

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).

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 CSV 文件转换为 xlsx 文件 Python 的相关文章

随机推荐