无法打开在python代码

时间:2017-12-21 02:37:09

标签: python excel csv

我使用python代码将一些.csv文件转换为.xls但是现在当我尝试打开文件时,它给了我一个错误:" COUNT_DIST2.xls无法访问。该文件可能已损坏,位于未响应的服务器上,或只读取#34;。 我在这个项目中创建了许多其他文件,它们都是.csv和.xls,但没有一个给我这个问题。我想我的代码可能在某些地方做错了。我非常确定这不是网络错误或办公室错误,因为我能够打开所有其他文档。

附件是代码:

import pandas as pd
import numpy as np
from xlrd import open_workbook
from xlwt import Workbook
from xlutils.copy import copy
from openpyxl import load_workbook
import matplotlib.pyplot as plt
import xlwt
import os
path = ('C:\Users\PETERemote\PycharmProjects\untitled\distributions')
data = []
count =1
count2 = 0
for files in os.listdir(path):
    if files.endswith("COUNT16_DISTRIBUTION" + str(count*1) + ".csv"):
        count += 1
count2 = count-2
print(count2)
#print(count2 = count)

count3=1
file_name = "COUNT16_DISTRIBUTION" + str(count3*1) + ".csv"
while (count3<=count2):
    with open(file_name) as f:
        for line in f:
            data.append([word for word in line.split("  ") if word])
    wb = xlwt.Workbook()
    output_file = open("COUNT16_DIST" + str(count3 * 1) + ".xls", 'w')
    count3 += 1
    sheet = wb.add_sheet("Sheet1")
    for row_index in range(len(data)):
        for col_index in range(len(data[row_index])):
            sheet.write(row_index, col_index, data[row_index][col_index])
    wb.save(output_file)
    data = []
    output_file.close()

1 个答案:

答案 0 :(得分:2)

以下是使用xlsxwriter的示例:

import os
import glob
import csv
from xlsxwriter.workbook import Workbook


for csvfile in glob.glob(os.path.join('.', '*.csv')):
    workbook = Workbook(csvfile[:-4] + '.xlsx')
    worksheet = workbook.add_worksheet()
    with open(csvfile, 'rt', encoding='utf8') as f:
        reader = csv.reader(f)
        for r, row in enumerate(reader):
            for c, col in enumerate(row):
                worksheet.write(r, c, col)
    workbook.close()

仅供参考,还有一个名为openpyxl的软件包,可以读/写Excel xlsx / xlsm文件,我测试过它并且工作正常。