首页 > 解决方案 > 有趣的 xlwings 问题:脚本在 Python 中有效,但在 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

标签: pythonexcelxlwingsfile-not-found

解决方案


感谢@Felix Zumstein 让我坚持文件路径解决方案。问题确实是文件路径问题。

我从 tkinter.askdirectory() 获取绝对文件路径并使用它来生成文本文件列表。然后我试图用JUST THE FILENAMES打开这些文本文件。这在 Python 中有效(可能是因为我在与文件相同的目录中运行脚本)但在 Excel 中无效。

为了解决这个问题,我必须将目录路径连接到列表中每个文件名的开头。然后我可以打开文件。然后我不得不从文件名中删除路径,以便将文件名用作 Excel 中工作表的名称。

将发布最终代码以确保完整性。


推荐阅读