I have written a program that reads all text files in a directory, loads them as tabular data into a dataframe, and then loads each dataframe into a new Excel worksheet in the same workbook. The intended purpose is to have the program be called from a button on a workbook that then loads all data in a directory.
The program runs fine in python with any directory and any text file...but not when called from within Excel.
This is the error that I get:
---------------------------
Error
---------------------------
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "h:\notebooks\augustine project\ramread.py", line 35, in data_reader clean_null_bytes(text_files) # Clean each file of null bytes
File "h:\notebooks\augustine project\ramread.py", line 76, in clean_null_bytes
with open(file, 'rb') as to_clean :
FileNotFoundError: [Errno 2] No such file or directory: '1 KPA COLUMN
BELOW REACTION TABLE.TXT'
So it is getting the correct path and filenames from that path but for some reason it seems that opening the files on the path is not working within Excel. Does Excel have a different way of interpreting a file path? I am really at a loss for next steps with this problem.
Any assistance or ideas is greatly appreciated.
Here is the program, below:
import os as os
from tkinter.filedialog import askdirectory,Tk
import pandas as pd
def main() :
Book = xl.Book.caller()
data_dictionary = data_reader()
for title, table in data_dictionary.items() :
Book.sheets.add(name = title)
Book.sheets[title].range("B2").value = table
def data_reader() -> dict :
folder = open_folder() # User selects folder on system
text_files = get_txt_files(folder) # Generate a list of text files in folder
clean_null_bytes(text_files) # Clean each file of null bytes
data_dict = tables_for_export(text_files) # Read the cleaned files as dataframes in a dict
return data_dict
def open_folder() -> str :
root = Tk()
root.withdraw()
root.update
folder = askdirectory()
root.destroy()
return folder
def get_txt_files(directory_path: str) -> list :
all_files = os.listdir(directory_path)
txt_files = [file for file in all_files if
(file[-4:] == ".txt") or #check the last four chars in file name
(file[-4:] == ".TXT")]
return txt_files
def clean_null_bytes(list_of_txt_files: list) :
for file in list_of_txt_files :
with open(file, 'rb') as to_clean :
raw_data = to_clean.read()
clean_data = raw_data.replace(b'\x00', b'')
with open(file, 'wb') as cleaned :
cleaned.write(clean_data)
return
def tables_for_export(list_of_txt_files: list) -> dict :
for_export = {}
for file in list_of_txt_files :
data_frame = pd.read_table(file)
for_export.update({file[:-4] : data_frame})
return for_export