Python Forum
read multiple .xlsx files and text files in a directory
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
read multiple .xlsx files and text files in a directory
#1
I have a list of .xlsx files (names 1.xlsx, 2.xlsx etc), each with several worksheet, in a directory. I need to insert data from its corresponding text file (named 1.txt, 2.txt etc) on the second worksheet named 'Filtered' and save it along with its original contents. The code I am trying is below. I end up with a blank worksheet in 'Filtered'. I am not sure how to read multiple text files with corresponding excel files and paste data. Any suggestions/edits on code ? Thank you

#!/usr/bin/python

import os
from openpyxl.reader.excel import load_workbook
import csv

directoryPath = r'/REPORTS/'
os.chdir(directoryPath)
folder_list = os.listdir(directoryPath)
for folders, sub_folders, file in os.walk(directoryPath):  
   for name in file:
       if name.endswith(".xlsx"):
           filename = os.path.join(folders, name)
           wb = load_workbook(filename, data_only=True)
           ws = wb.get_sheet_by_name('Filtered')
           directory = os.path.join("/REPORTS/temp", "path")
           for root,dirs,files in os.walk(directory):
               for file in files:
                   if file.endswith(".txt"):
                       f = open(textfile, 'r')
                       reader = csv.reader(f, delimiter='\t')
                       for row in reader:
                           ws.append(row)
                           wb.save(filename)
Reply


Messages In This Thread
read multiple .xlsx files and text files in a directory - by BNB - Jun-02-2017, 11:14 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Best fit for SVG files chihuahua998 3 990 May-04-2025, 09:25 AM
Last Post: cohik
  Copying Data from Multiple XLS Files to a Cumulative Master File Martijn 3 1,299 Apr-05-2025, 05:07 AM
Last Post: Pedroski55
  header files (python3-dev) ZZBBD 3 1,399 Aug-04-2024, 06:49 PM
Last Post: markjohn8348
  Import multiple CSV files into pandas Krayna 0 2,333 May-20-2021, 04:56 PM
Last Post: Krayna
  Python - Pandas writing blank files to file tdunphy 0 2,582 Jan-14-2021, 12:11 AM
Last Post: tdunphy
  Most Compatible Text Editor to Handle Large Files? Robotguy 2 3,357 Aug-18-2020, 03:51 PM
Last Post: FortyTwo
  Creating many csv files from Pandas EMA 0 2,184 Jul-26-2020, 06:39 PM
Last Post: EMA
  Loading multiple JSON files to create a csv 0LI5A3A 0 2,845 Jun-28-2020, 10:35 PM
Last Post: 0LI5A3A
  Binning data to files Kappel 4 3,597 Jun-22-2020, 06:25 PM
Last Post: Kappel
  Filter rows by multiple text conditions in another data frame i.e contains strings an Pan 0 2,701 Jun-09-2020, 06:05 AM
Last Post: Pan

Forum Jump:

User Panel Messages

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