簡體   English   中英

有趣的xlwings問題:腳本可在Python中工作,但不能從Excel中工作

[英]Funny xlwings issue: script works in Python but not from Excel

我編寫了一個程序,該程序讀取目錄中的所有文本文件,將它們作為表格數據加載到數據框中,然后將每個數據框加載到同一工作簿中的新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

謝謝@Felix Zumstein讓我堅持使用文件路徑解決方案。 該問題確實是文件路徑問題。

我從tkinter.askdirectory()獲取了絕對文件路徑,並使用它來生成文本文件列表。 然后,我試圖使用JUST THE FILENAMES打開這些文本文件。 這在Python中有效(可能是因為我在與文件相同的目錄中運行了腳本),但在Excel中卻沒有。

要解決此問題,我必須將目錄路徑連接到列表中每個文件名的開頭。 然后,我可以打開文件。 然后,我必須從文件名中刪除路徑,然后才能使用文件名作為Excel中工作表的名稱。

將發布最終代碼以確保完整性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM