Kristada673
Kristada673

Reputation: 3744

Write to file not working in Python 3.5

I wrote the following code to take the fourth column of an xlsx file and save it in a csv file, if that matters. But it gives the following error: ValueError: write to closed file.

from __future__ import division, print_function
import sys
import numpy as np
import csv
import os
import xlrd
import csv
import unicodecsv

def xls_to_csv1(xls_filename, csv_filename):
    wb = xlrd.open_workbook(xls_filename)
    sh = wb.sheet_by_index(0)

    with open(csv_filename,"wb") as fh:
        csv_out = unicodecsv.writer(fh, encoding='utf-8', delimiter=';')

    #print(sh.row_values(1)[3])

    for row_number in range (1, sh.nrows):
        row = []
        count=0
        for col in sh.row_values(row_number):
                if count==3:
                    row.append(col)
                count=count+1
                csv_out.writerow(row)

xls_filename='Attachment_1_Test_Data_1_Seed.xlsx'
csv_filename='Summary_csv.csv'
xls_to_csv1(xls_filename,csv_filename)

Upvotes: 0

Views: 357

Answers (1)

Abdou
Abdou

Reputation: 13274

The process of appending data to the csv file should be done inside the with_statement. This is because a with_statement is supported through what is known as context manager. Basically, it means that if you open a file with a with_statement, then exiting the with_statement closes the file. That's why you're seeing the closed file error. The following should do:

from __future__ import division, print_function
import sys
import numpy as np
import csv
import os
import xlrd
import csv
import unicodecsv

def xls_to_csv1(xls_filename, csv_filename):
    wb = xlrd.open_workbook(xls_filename)
    sh = wb.sheet_by_index(0)

    with open(csv_filename,"wb") as fh:
        csv_out = unicodecsv.writer(fh, encoding='utf-8', delimiter=';')
        #print(sh.row_values(1)[3])

        for row_number in range (1, sh.nrows):
            row = []
            count=0
            for col in sh.row_values(row_number):
                if count==3:
                    row.append(col)
                count=count+1
            csv_out.writerow(row)

I hope this helps.

Upvotes: 2

Related Questions