1

I am trying to put the data from csv files into excel files in python 2.7 windows 7. Every time i use the following function the python does convert the csv to the respective files and names it but here is the problem. I want the data of one csv file to be copied to it's respective excel file and the data of second csv in the second excel file but what mistake i am making is that after the first excel is create , the data of this first excel gets copied to the second excel file. So the second excel in addition to it's own data from the csv file has the data from 1st excel. And the 3rd excel has the data of 1st excel +2nd excel and 3rd excel. Can anyone tell me what am i doing wrong ? Attached is the code :

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-1
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.insert([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)
    output_file.close()
1
  • Could you correct the indentation of the code in your post? Commented Dec 16, 2017 at 8:05

1 Answer 1

1

You only add things to data.

That's why each output file has the contents of all the input files so far.

You should clear data right after saving the output file:

wb.save(output_file)
data = []
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.