Python Forum
Add a new column when I extract each sheet in an Excel workbook as a new csv file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Add a new column when I extract each sheet in an Excel workbook as a new csv file
#1
Below is a python script is to extract each sheet in an Excel workbook as a new csv file.Want to Add a new column when I extract each sheet in an Excel workbook as a new csv file. The new column is added at the end of last column of every file. Can anyone help me how to do this??
'''This python script is to extract each sheet in an Excel workbook as a new csv file'''
import csv
import xlrd
import sys
import pandas as pd

def ExceltoCSV(excel_file, csv_file_base_path):
    workbook = xlrd.open_workbook(excel_file)
    for sheet_name in workbook.sheet_names():
        print('processing - ' + sheet_name)
        worksheet = workbook.sheet_by_name(sheet_name)
        csv_file_full_path = csv_file_base_path + sheet_name.lower().replace(" - ", "_").replace(" ","_") + '.csv'
        csvfile = open(csv_file_full_path, 'w')
        writetocsv = csv.writer(csvfile, quoting = csv.QUOTE_MINIMAL)
        for rownum in range(worksheet.nrows):
            writetocsv.writerow(
                list(x.encode('utf-8') if type(x) == type(u'') else x for x in worksheet.row_values(rownum)
                )
            )
            #writetocsv.writerow(rownum.append(sheet_name)) #Adding a new column
        csvfile.close()


if __name__ == '__main__':
    ExceltoCSV(excel_file = sys.argv[1], csv_file_base_path = sys.argv[2])
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  module 'openpyxl.workbook' has no attribute 'active' lsaavedra21 5 2,014 Oct-30-2024, 06:26 PM
Last Post: lsaavedra21
  JSON File - extract only the data in a nested array for CSV file shwfgd 2 1,231 Aug-26-2024, 10:14 PM
Last Post: shwfgd
  Extract and rename a file from an Archive tester_V 4 4,219 Jul-08-2024, 07:54 AM
Last Post: tester_V
  docx file to pandas dataframe/excel iitip92 1 3,126 Jun-27-2024, 05:28 AM
Last Post: Pedroski55
  Python openyxl not updating Excel file MrBean12 1 2,319 Mar-03-2024, 12:16 AM
Last Post: MrBean12
  Copy Paste excel files based on the first letters of the file name Viento 2 1,707 Feb-07-2024, 12:24 PM
Last Post: Viento
  Help copying a column from a csv to another file with some extras g0nz0uk 3 1,974 Feb-01-2024, 03:12 PM
Last Post: DeaD_EyE
  Search Excel File with a list of values huzzug 4 3,059 Nov-03-2023, 05:35 PM
Last Post: huzzug
  Updating sharepoint excel file odd results cubangt 1 2,213 Nov-03-2023, 05:13 PM
Last Post: noisefloor
  How to copy work sheet data one workbook to other? sayyedkamran 2 1,673 Nov-03-2023, 09:10 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020