xlwings调用一个应该创build一个文件的python函数,但是没有文件被创build

def create_file(): file_writer= open('testFile.txt','w') file_writer.write('TESTING...;\n') file_writer.flush() file_writer.close() def my_macro(): wb = Workbook.caller() # Creates a reference to the calling Excel file Range('Sheet1', 'C3').value = random.randint(0,10) updateValue = Range('Sheet1', 'C3').value print("updatedValue=" , updateValue); create_file() if __name__ == '__main__': path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'FirstExcel.xlsm')) Workbook.set_mock_caller(path) my_macro() 

当我在Eclipse中运行上面的代码时,它创build一个文件并更新Excel电子表格。 但是,当我从Excel中运行它更新电子表格,但不会创build一个文件。

问题是,当前Excel启动Python解释器的工作目录不同于从Python调用文件的时候。 这是GitHub上的一个开放性问题,请看这里 。

同时,只需使用绝对/完整pathopenwrite所有文件。 你也应该可以使用像os.path.abspath(os.path.join(os.path.dirname(__file__), 'testFile.txt'))