Я написал программу, которая считывает все текстовые файлы в каталоге, загружает их в виде табличных данных в кадр данных, а затем загружает каждый кадр данных в новый лист Excel в той же книге. Предполагаемая цель - вызвать программу из кнопки на рабочей книге, которая затем загружает все данные в каталог.
Программа отлично работает на python с любым каталогом и любым текстовым файлом ... но не при вызове из Excel.
Это ошибка, которую я получаю:
---------------------------
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'
Таким образом, он получает правильный путь и имена файлов по этому пути, но по некоторым причинам кажется, что открытие файлов по пути не работает в Excel. Есть ли в Excel другой способ интерпретации пути к файлу? Я действительно в недоумении для следующих шагов с этой проблемой.
Любая помощь или идеи приветствуются.
Ниже приведена программа:
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